fastjson,,,是十分流行的json解析工具,阿里巴巴的开源产品,十分好用。



一。配置流程




(1). 需要在 pom.xml 中配置

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>

(2). 在spring mvc的配置文件spring-mvc.xml,添加 以json形式输出。

<mvc:annotation-driven>
        <mvc:message-converters>
            <bean id="fastJsonHttpMessageConverter"
                  class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

这样配置,返回的对象,会被自动转成json形式输出

(3). 在Controller 中返回对象,,(list,map集合也可以)

@RequestMapping("/get_users_json")
    @ResponseBody
    public Map<Integer, User> getUsers() {
        Map<Integer, User> users = new HashMap();
        users.put(1,new User("刘备", 1));
        users.put(2,new User("关羽", 2));
        users.put(3,new User("张飞", 3));
        users.put(4,new User("诸葛亮", 4));
        return users;
    }

(4).返回结果如下:(格式化后)

{
    "1": {
        "id": 1, 
        "name": "刘备"
    }, 
    "2": {
        "id": 2, 
        "name": "关羽"
    }, 
    "3": {
        "id": 3, 
        "name": "张飞"
    }, 
    "4": {
        "id": 4, 
        "name": "诸葛亮"
    }
}


二。注意细节




(1). 需要配置 注解 @ResponseBody,否则会springMVC转json输出出现404错误,,


原因是找不到返回的形式,spring 默认是返回字符串,转 ModelAndView。加上注解直接返回内容(即json)

(2). fastjson的bean配置,list中的顺序不能变,,可能会出现问题

<bean id="fastJsonHttpMessageConverter"
                  class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>