首页 > 代码库 > json jackson
json jackson
1.引入依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.3</version> </dependency>
2.添加 conventer
<mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper" ref="objectMapper" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:indentOutput="false" p:simpleDateFormat="yyyy-MM-dd‘T‘HH:mm:ss.SSSZ" />
indentOutput 缩进打印,false 无缩进 ,true 有缩进(格式化)
{ "b" : "你好", "a" : "2016-10-06T14:54:16.918+0800"}
{"b":"你好","a":"2016-10-06T14:57:33.724+0800"}
simpleDateFormat 可以将日期类型自动转为指定格式字符串
具体用法可以查看该类
MappingJackson2HttpMessageConverter
By default, this converter supports application/json and application/*+json with UTF-8 character
set. This can be overridden by setting the supportedMediaTypes property.
这样重写
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean>
3. 设置controller 的 response
关于controller 返回时由哪个 conventer 处理的问题
首先 如果不是加 @ResponseBody 则由viewresolver 处理
在 @Controller + @ResponseBody = @RestController
You can use the new @RestController annotation with Spring MVC applications, removing the need to add @ResponseBody to each of your @RequestMapping methods.
这种情况下 converter就生效了,会根据 Content-Type:text/html;charset=ISO-8859-1 类型分配给具体的 converter 处理
默认有一个
2016-10-06 15:39:48 DEBUG RequestResponseBodyMethodProcessor:250 - Written [你好] as "text/html" using [org.springframework.http.converter.StringHttpMessageConverter@407305a3]
这个默认的 StringHttpMessageConverter 使用的编码是
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
可以覆盖这个 converter
<bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean>
有这么多 HttpMessageConverter 视情况增加到 <mvc:message-converters>...
json jackson