jackson使用步骤:
1,导入jackson的依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2,解决json乱码问题(在springmvc-servlet.xml中):
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3,编写Controller层代码
@Controller
//@RestController
public class UserController {
@RequestMapping("/j1")
@ResponseBody
public String json1() throws JsonProcessingException {
//创建一个mapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user=new User("周歪1号",21,"男");
String str = mapper.writeValueAsString(user);
return str;
}
}
注意点: 1,注解Controller和ResponseBody组合使用可以返回给前端一个字符串
2,RestController可以单独使用返回给前端一个字符串
原文:https://www.cnblogs.com/zhouwai/p/15135101.html