SpringMVC:json消息处理器

<mvc:annotation-driven/>初始化7个转换器

  • ByteArrayHttpMessageConverter 

  • StringHttpMessageConverter 

  • ResourceHttpMessageConverter 

  • SourceHttpMessageConverter 

  • XmlAwareFormHttpMessageConverter 

  • Jaxb2RootElementHttpMessageConverter 

  • MappingJacksonHttpMessageConverter


对于json的解析就是通过MappingJacksonHttpMessageConverter转换器完成的。

只添加<mvc:annotation-driven />还不行,需要在classpath环境中能找到Jackson包

Jackson包Maven配置

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-core-asl</artifactId>
  <version>1.9.13</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.4</version>
</dependency>

之前看资料有说过spring4.x之后就需要配置MappingJackson2HttpMessageConverter而不是默认的MappingJacksonHttpMessageConverter。而相应的jar包也需要使用对应的2.x版本

<mvc:annotation-driven>  
        <mvc:message-converters register-defaults="true">  
         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">             <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
         </bean> 
        </mvc:message-converters>
        <!--注入的message-converters优先级高于默认注入的json转换器-->
</mvc:annotation-driven>

注意:默认情况下MappingJacksonHttpMessageConverter 会设置content为application/json,在IE9下返回会出现提示下载的现象,出现这种情况可以手动指定头信息为"text/html",或者"/"(所有,不确定就设置为这个)。

当只设置了"text/html"时,我试验的时候Ajax回调函数接收json值的时候不行,确实是传递过来了,但是也许是转换出了问题,所以在上面还加了个“application/json”就可以了。。。。。


当然也可以用fastjson,不过依赖的jar包就不一样了,而且配置消息处理器的方式也是需要自己添加的。

转载于:https://my.oschina.net/u/1020238/blog/533885

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值