When not using the spring framework, we convert the object into json by importing the jar package, and then write the following code
// 使用json的转换工具将对象转换成json格式字符串再返回
// 原生形式
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
After using SpringMVC, this operation can be handed over to spring to do
- Import the mvc namespace in the spring-mvc.xml configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
That is to add these two sentences
- Configure annotation driver
<mvc:annotation-driven/>
- Test results
I use a User object to test, there are only two attributes in the User class: username and age
// 回写json格式
@RequestMapping("/testReturnJson")
@ResponseBody
// 期望spring框架将对象直接转换成json对象
public User test(){
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
return user;
}
operation result