json

json在服务器端应用大致分为2类: 1,接受并解析客户端发送给服务器的json数据 2,服务器向客户端发送json数据 下面分别说一下这2方面的应用: 1,接受并解析客户端发送给服务器的json数据 如果客户端发送给服务器的数据是 {name:'hello',obj:['age','13']} 服务器端程序如下: package com.test; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /*+++++++++++++++++++++++++++++++++++++++++++++++++ +@author lzh +Description: +Copyright:Copyright 2008 HULIZHONG +Author:lzh([email protected]) +History: ++++++++++++++++++++++++++++++++++++++++++++++++++*/ public class JSONHandler { public void parseJSON(String jsonStr) throws Exception{ //参数jsonStr的值为{name:'hello',obj:['age','13']} String name=null,age=null; JSONObject jSONObject=new JSONObject(jsonStr); name=(String)jSONObject.get("name"); //name的值应是hello age=((JSONObject)jSONObject.get("obj")).get("age"); //age的值应是13 } } 上面的程序就完成了服务器端对客户端发送json数据的解析工作,再获取name,age值后,即可进行其它业务逻辑处理! 2,服务器向客户端发送json数据 package com; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; /*+++++++++++++++++++++++++++++++++++++++++++++++++ +@author lzh +Description: +Copyright:Copyright 2008 HULIZHONG +Author:lzh([email protected]) +History: ++++++++++++++++++++++++++++++++++++++++++++++++++*/ public class JSONResponse { public void jsonResponse(HttpServletResponse response) throws Exception { //向客户端发送数据:{name:'hello',obj:['age','13']} JSONObject obj1 = new JSONObject(); JSONObject obj2 = new JSONObject(); obj2.put("age", "13"); obj1.put("name", "hello"); obj1.put("obj", obj2); response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); //obj1.toString()即为{name:'hello',obj:['age','13']} response.getWriter().print(obj1.toString()); } } 上述代码即为完成了服务端向客户端发送json数据的解析工作,客户端在接受{name:'hello',obj:['age','13']}数据后 根据具体业务要求进行数据处理

你可能感兴趣的:(json)