1. 程式人生 > >SpringMVC:JSON形式輸出(基於Fastjson)

SpringMVC:JSON形式輸出(基於Fastjson)

在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.測試結果:

執行結果