@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