springmvc返回json(使用jackson的方式)

现在多数的应用为了提高交互性多使用异步刷新,即在不刷新整个页面的情况下,只刷新局部,局部刷新用得最多就是ajax,ajax和后台进行交互的数据格式使用的最多的是JSON,这里简单描述,在springmvc的开发架构下如何返回JSON串。有两种方式进行配置,一:fastjson;二、jackson,因为用到了jackson这种方式,下面就讲讲jackson的方法(后面有时间会将fastjson的方式补上):

       1. jackson是另外一种把java对象转化为json对象的jar包,要使用此种方式需要引入以下三个jar包:jackson-annotations-2.5.0-rc4.jar、jackson-core-2.5.0-rc4.jar、jackson-databind-2.5.0-rc4.jar,下面是在配置文件applicationContext.xml中的配置:

       

 <!-- 设置返回json的编码格式 -->
<bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
     <property name="supportedMediaTypes">
         <list>
             <value>application/json;charset=UTF-8</value>
         </list>
     </property>
 </bean>
 <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
     <property name="messageConverters">
         <list>
             <ref bean="stringConverter" />
             <ref bean="jsonConverter" />
         </list>
     </property>
 </bean>
 
 
pom文件中的配置:
 
 
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version>
</dependency>
此处设置完编码格式,在controller写接口,就不用在produces中设置编码格式防止乱码,这里会将所有返回的json数据编码格式转为utf-8

猜你喜欢

转载自blog.csdn.net/qq_35673617/article/details/78914633
今日推荐