json与字符串的互转
在spring框架中当ajax请求需要返回json数据时,我们只需要在@RequestMapping后面加上@ResponseBody,即可为我们返回想要的json。
下面我们讲解json与字符串的互转方式各两种:
function ceshi(){ $.ajax({ type:'get', url:'${ctx}/secondPhase/customCombotreeData.pt?id=201711281652407353448711985811', success:function(data){ console.log('$$'+data[0].id); //json转字符串 var obj1 = JSON.stringify(data); var obj2 = JSON.stringify(data); console.log('json转字符串obj1:'+obj1); console.log('json转字符串obj2:'+obj2); //字符串转json var json1 = $.parseJSON(obj1); var json2 = JSON.parse(obj2); console.log('json转字符串json1:'+json1); console.log('json转字符串json2:'+json2); //获取json对象属性值: for ( var int = 0; int < json1.length; int++) { var json1id = json1[int].id; var json1text = json1[int].text; console.log(json1id+':'+json1text); var json1children = json1[int].children; for ( var int2 = 0; int2 < json1children.length; int2++) { var json1childrenid =json1children[int2].id; var json1childrentext =json1children[int2].text; console.log(json1childrenid+':'+json1childrentext); } } } }); }
控制台输出:
3>Javascript支持的转换方式:
eval('(' + jsonstr + ')'); //可以将json字符串转换成json对象,注意需要在json字符外包裹一对小括号
注:ie8(兼容模式),ie7和ie6也可以使用eval()将字符串转为JSON对象,但不推荐这些方式,这种方式不安全eval会执行json串中的表达式。
4>JSON官方的转换方式:
http://www.json.org/提供了一个json.js,这样ie8(兼容模式),ie7和ie6就可以支持JSON对象以及其stringify()和parse()方法;
可以在https://github.com/douglascrockford/JSON-js上获取到这个js,一般现在用json2.js。