JSON处理数据
js、java处理json数据方法
一:js处理json数据
处理办法之一是把本机json数据或远程返回json数据用eval函数,使之变成DOM对象。
例如:
varpeople={
"programmers":[{"firstName":"Elie","lastName":"Harld","email":"[email protected]"}],
"authors":[{"firstName":"Isac","lastName":"Asiov","genre":"sciencefiction"}],
"musicians":[{"firstName":"Eric","lastName":"Claon","instrument":"guitar"},
{"firstName":"Seei","lastName":"Rnoff","instrument":"piano"}]
};
二:Java处理json数据
varurl="parseJson.do?people="+escape(people.toJSONString());
java文件
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importnet.sf.json.JSONObject;
importnet.sf.json.JSONArray;
publicclassJsonActionextendsAction{
@Override
publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{
Stringparam=request.getParameter("people");
JSONObjectjsonObj=JSONObject.fromObject(param);
for(Iteratoriter=jsonObj.keys();iter.hasNext();){//先遍历整个people对象
Stringkey=(String)iter.next();
System.out.println(key);
JSONArrayarray=jsonObj.getJSONArray(key);
for(inti=0;i<array.size();i++){//再遍历整个三个属性(programmers,authors,musicians)的值(数组)
JSONObjectobject=(JSONObject)array.get(i);
for(Iteratoriterator=object.keys();iterator.hasNext();){//最后遍历值中的每个属性
Stringkey2=(String)iterator.next();
System.out.print(""+key2+":"+object.get(key2));
}
System.out.println();
}
System.out.println();
}
//最终输出如果如下:
programmers
firstName:ElielastName:Harldemail:[email protected]
authors
firstName:IsaclastName:Asiovgenre:sciencefiction
musicians
firstName:EriclastName:Claoninstrument:guitar
firstName:SeeilastName:Rnoffinstrument:piano
}