配置json类型转换又是怎样的
时间: 2024-02-22 22:54:41 浏览: 25
在Spring框架中,我们可以通过配置HttpMessageConverter来实现Java对象和JSON格式的相互转化。具体步骤如下:
1. 导入Jackson库的依赖。
2. 在Spring的配置文件中,配置MappingJackson2HttpMessageConverter,即在<mvc:annotation-driven>标签下添加以下配置:
```xml
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
```
3. 在Controller中,使用@ResponseBody注解将Java对象转换成JSON格式的字符串,或者使用@RequestBody注解将JSON格式的字符串转换成Java对象。
示例代码如下:
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/get")
@ResponseBody
public User getUser() {
// 创建一个Java对象
User user = new User();
user.setName("张三");
user.setAge(18);
user.setGender("男");
return user;
}
@RequestMapping("/save")
@ResponseBody
public String saveUser(@RequestBody User user) {
// 保存用户信息
return "保存成功!";
}
}
class User {
private String name;
private int age;
private String gender;
// getter和setter方法省略
}
```
以上代码中,getUser()方法使用@ResponseBody注解将Java对象转换成JSON格式的字符串返回给前端页面,saveUser()方法使用@RequestBody注解将前端页面传递过来的JSON格式的字符串转换成Java对象。
这样配置后,Spring框架就可以自动将Java对象和JSON格式的字符串相互转化了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)