springmvc中json格式处理

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")
@ResponseBody
public 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-----------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值