JSON使用总结

1、要使用JSON,先下下载json.js文件。下载地址:https://github.com/douglascrockford/JSON-js

定义一个json对象
var jsonObject={};
给对象属性赋值
jsonObject.productId=123;
jsonObject.singleType=1;

json数组
var jsonArray = new Array();
jsonArray.push(jsonObject);
可以用jquery的each进行循环
$.each(jsonArray,function(index,jsonObject){

})

从json对象获取值
var productId=jsonObject.productId;

将json对象转换成字符串,用于将值放到隐藏域传到后台
var jsonString  = JSON.stringify(jsonObject);
{"productId":123,"singleType":1}

JSON这个工具下面的两个js工具类提供的,已经在模板上对所有ftl页面进行引用了	    

如果是转换数组结果为
[{"productId":123,"singleType":1},{"productId":456,"singleType":2}]

将json格式字符串转换成对象,用于从隐藏域获取value后,转换成对象来操作
var jsonObject = JSON.parse('{"productId":123,"singleType":1}');
var jsonArray = JSON.parse('[{"productId":123,"singleType":1},{"productId":456,"singleType":2}]');

java:
隐藏域中的json字符串传到后台后转换成JSONObject对象
JSONObject jb = JSONObject.fromObject("{\"productId\":123,\"singleType\":1}");
从jsonobject获取属性
Long productId = jb.getLong("productId");
Double price = jb.getDouble("price");
如果jb中没有productId属性,则会抛异常

json数组JSONArray
JSONArray js = JSONArray.fromObject("[{\"productId\":123,\"singleType\":1},{\"productId\":456,\"singleType\":2}]");
然后循环成JSONObject来获取属性

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值