springmvc中json格式处理
Demo:
1.导入jackon-all-1.7.6.jar包
2.在entity包中创建Json类
------------start-------------------package com.springmvc.entity;
/*** 在公司的开发中,这个类一般会设置三个属性* 1,标识数据是完整的* 2,设置自定义信息* 3,数据的主体* */public class Json {private boolean flag;private String msg;private Object obj;
//get set...}------------end-------------------
3.在Controller中
----------start-----------------@RequestMapping("/testjson")@ResponseBodypublic Json testJson(){Json json = new Json();json.setFlag(true);json.setMsg("数据查询成功");List<City> citys = new ArrayList<City>();citys.add(new City(1,"北京市"));citys.add(new City(2,"天津市"));citys.add(new City(3,"上海市"));citys.add(new City(4,"重庆市"));json.setObj(citys);return json;}----------end-----------------
4.创建city类
package com.springmvc.entity;
public class City {private Integer cid;private String cname;public City() {
}public City(Integer cid, String cname) {this.cid = cid;this.cname = cname;}//get set...}
5.jsp页面
测试按钮:<input type="button" value="test json" id="btn"/>jquery代码:----------start-----------------<script type="text/javascript" src="js/jquery-1.7.2.js"></script><script type="text/javascript">$(function(){$('#btn').click(function(){$.ajax({type: 'post',url: 'test1controller/testjson.do',data:{},success: function(result){console.info(result);console.info(result['flag']);console.info(result['msg']);console.info('----------------');console.info(result['obj'].length);for(var i=0;i<result['obj'].length;i++){console.info(result['obj'][i].cid+'-----'+result['obj'][i].cname);}console.info('----------------');}});});});</script>----------end-----------------