SpringMVC:JSON形式输出(基于Fastjson)

北战南征 提交于 2020-03-23 09:32:34

在Spring3.0中,@ResponseBody标记可以将对象”封装”为JSON形式的数据,并输出,下面的例子中使用的是阿里的Fastjson JSONaz解析工具,在spring配置文件中加入一些额外的配置。

1.依赖配置

<properties>
    <spring.version>4.1.4.RELEASE</spring.version>
    <fastjson.version>1.2.11</fastjson.version>
    <javax.servlet.version>2.5</javax.servlet.version>
    <jackson.version>1.9.10</jackson.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${javax.servlet.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

2.一个POJO,要转换为JSON输出的对象

public class shop {
    private String name;
    private String[] staffName;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String[] getStaffName() {
        return staffName;
    }

    public void setStaffName(String[] staffName) {
        this.staffName = staffName;
    }
}

3.servlet-context.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!-- 注意!SpringMVC的配置文件使用的是mvc命名空间 -->
<beans:beans xmlns:context="http://www.springframework.org/schema/context"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns="http://www.springframework.org/schema/mvc"
             xmlns:task="http://www.springframework.org/schema/task"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.mkyong.common.controller" />

    <annotation-driven>
        <message-converters register-defaults="true">
            <!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
            <beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <beans:constructor-arg value="UTF-8"/>
            </beans:bean>
            <!-- 配置Fastjson支持 -->
            <beans:bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <beans:property name="charset" value="UTF-8"/>
                <beans:property name="supportedMediaTypes">
                    <beans:list>
                        <beans:value>application/json</beans:value>
                        <beans:value>text/html;charset=UTF-8</beans:value>
                    </beans:list>
                </beans:property>
                <beans:property name="features">
                    <beans:list>
                        <beans:value>WriteMapNullValue</beans:value>
                        <beans:value>QuoteFieldNames</beans:value>
                        <beans:value>WriteDateUseDateFormat</beans:value>
                        <beans:value>WriteEnumUsingToString</beans:value>
                    </beans:list>
                </beans:property>
            </beans:bean>
        </message-converters>
    </annotation-driven>
    <beans:bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>
</beans:beans>

4.web.xml文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>json output</display-name>
  <servlet>
    <servlet-name>dispatchServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatchServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

5.controller类

@Controller
@RequestMapping("/kfc/brands")
public class JSONController {

    @RequestMapping(value = "{name}",method = RequestMethod.GET)
    public @ResponseBody shop getShopInJSON(@PathVariable String name)
    {
        shop sp = new shop();
        sp.setName(name);
        sp.setStaffName(new String[]{"Staffname1","Staffname2"});
        return sp;
    }
    //测试用
    @RequestMapping("")
    public String index()
    {
        return "index";
    }
}

6.测试结果:

运行结果

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!