其他分享
首页 > 其他分享> > spring-JSON

spring-JSON

作者:互联网

1.导入maven依赖,导入后记得到lib包下查看是否添加成功:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>

2.直接在Controller中使用@ResponseBody标签会使返回的字符串不走视图解析器,直接在页面返回结果,@RestController标签使整个类下的方法都不走视图解析器,直接在页面返回结果:

//转换JSON数据
@RequestMapping("/json1")
@ResponseBody
public String json1() throws JsonProcessingException {
User user = new User("2022","吴清风","男");
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(user);
return str;
}

JSON乱码问题解决:

<!--JSON乱码问题配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<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>

在spring配置文件中配置

 

标签:jackson,spring,视图,JSON,json1,ObjectMapper
来源: https://www.cnblogs.com/wyjx/p/15861706.html