javascript 处理json相关
1 function showJSON() { 2 var user = 3 { 4 "username":"andy", 5 "age":20, 6 "info": { "tel": "123456", "cellphone": "98765"}, 7 "address": 8 [ 9 {"city":"beijing","postcode":"222333"}, 10 {"city":"newyork","postcode":"555666"} 11 ] 12 } 13 14 alert(user.username); 15 alert(user.age); 16 alert(user.info.cellphone); 17 alert(user.address[0].city); 18 alert(user.address[0].postcode); 19 }
1 function showJSON() { 2 var user = 3 { 4 "username":"andy", 5 "age":20, 6 "info": { "tel": "123456", "cellphone": "98765"}, 7 "address": 8 [ 9 {"city":"beijing","postcode":"222333"}, 10 {"city":"newyork","postcode":"555666"} 11 ] 12 } 13 14 alert(user.username); 15 alert(user.age); 16 alert(user.info.cellphone); 17 alert(user.address[0].city); 18 alert(user.address[0].postcode); 19 20 user.username = "Tom"; 21 alert(user.username); 22 }
JSON提供了json.js包,下载http://www.json.org/json.js 后,将其引入然后就可以简单的使用object.toJSONString()转换成JSON数据。
1 function showCar() { 2 var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); 3 alert(carr.toJSONString()); 4 } 5 6 function Car(make, model, year, color) { 7 this.make = make; 8 this.model = model; 9 this.year = year; 10 this.color = color; 11 }
或者直接用eval来获得json对象,eval直接获得从后台获取的json str
function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = eval('(' + str + ')'); alert(obj.toJSONString()); }
或者使用parseJSON()方法
function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = str.parseJSON(); alert(obj.toJSONString()); }
prototype-1.5.1.js中提供了JSON的方法,String.evalJSON(), 可以不使用json.js, 修改上面的方法
function jsonResponse(originalRequest) { alert(originalRequest.responseText); var myobj = originalRequest.responseText.evalJSON(true); alert(myobj.name); }
JSON还提供了java的jar包 http://www.json.org/java/index.html API也很简单,下面举个例子
function sendRequest() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); var pars = "car=" + carr.toJSONString(); var url = "/MyWebApp/JSONTest1"; var mailAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: jsonResponse } ); }
使用JSON请求字符串就可以简单的生成JSONObject并进行解析,修改servlet添加JSON的处理(要使用json.jar)
private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException { String s3 = request.getParameter("car"); try { JSONObject jsonObj = new JSONObject(s3); System.out.println(jsonObj.getString("model")); System.out.println(jsonObj.getInt("year")); } catch (JSONException e) { e.printStackTrace(); } response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }"); }
feiyue3008