@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包

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM