js处理json数据,java处理json数据
一.js处理json数据
处理办法之一是把本机json数据或远程返回json数据用eval函数,使之变成DOM对象。
例如:
var people = { "programmers": [{ "firstName": "Elliotte", "lastName":"Harold","email": "elharo@macfaq.com" }],
"authors": [{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }],
"musicians": [{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }]
};
var obj = eval('(' + str + ')');
alert(obj.programmers);
二.Java处理json数据
var url = "parseJson.do?people=" + escape(people.toJSONString());
java 文件
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
public class JsonAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String param=request.getParameter("people");
JSONObject jsonObj=JSONObject.fromObject(param);
JSONArray array=jsonObj.getJSONArray("programmers");
System.out.println("array:"+array.get(0));
JSONObject obj=jsonObj.getJSONObject("singer");
System.out.println("obj:"+obj.get("firstName"));
}