SpringMVC:json消息处理器

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

  • ByteArrayHttpMessageConverter spring

  • StringHttpMessageConverter json

  • ResourceHttpMessageConverter mvc

  • SourceHttpMessageConverter app

  • XmlAwareFormHttpMessageConverter 函数

  • Jaxb2RootElementHttpMessageConverter spa

  • MappingJacksonHttpMessageConvertercode


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

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

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包就不同了,并且配置消息处理器的方式也是须要本身添加的。

相关文章
相关标签/搜索