@ResponseBody将集合数据转换为json格式并返回给客户端

spring-mvc.xml:

<beans 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    >
<mvc:annotation-driven/>

或者:

<mvc:annotation-driven>
     <mvc:message-converters register-defaults="false">
           <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>

 

js代码:

$.post("${pageContext.request.contextPath}/getJson",{},function(data){                 
    alert(JSON.stringify(data));
});

java代码:

@RequestMapping("/getJson")
@ResponseBody
public List<User> getJson(){
    List<User> list = new ArrayList<User>();
    User user1 = new User(10, "刘德华", 45);
    User user2 = new User(12, "张学友", 46);
    list.add(user1);
    list.add(user2);
    return list;
}

导入jackson的Jar包

 或者fastjson的Jar包

 

posted @ 2017-12-18 15:14  如果屈原会编程  阅读(6900)  评论(0编辑  收藏  举报