在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。