SpringMVC-JSON-04
JSON:数据交换格式
文本格式
JSON和JavaScript对象互换
JSON->JavaScript
var obj = JSON.parse(json)
JavaScript->JSON
JSON.stringify(user);
JSON解析工具
Jackson
- pom配置导入jar包
- 增加乱码配置
- 类中new ObjectMapper对象
- 用mapper的writeValueAsString方法
中文乱码解决:
方法1
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
方法2
<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>
fastJson
PS:@ResponseBody//直接返回字符串,不走视图解析器;@RestController不走视图解析器
fastJson
引入依赖包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>
使用时直接JSON.方法,如:JSON.parse,JSON.toJSONString
@RequestMapping(value = "/j6")
public String json6() throws JsonProcessingException {
User user = new User(1, "的", "123", "shen");
User user1 = new User(1, "的", "123", "shen");
User user2 = new User(1, "的", "123", "shen");
User user3 = new User(1, "的", "123", "shen");
List<User> userList = new ArrayList<User>();
userList.add(user);
userList.add(user1);
userList.add(user2);
userList.add(user3);
String str = JSON.toJSONString(userList);
return str;
}