在正式解析之前,我们需要下载解析Json所需要的jar包,一共有7个。
下载地址如下:https://download.csdn.net/download/zai_xia/10374080
大家也可以自行找资源下载。
然后将这些Jar包 Build Path 进项目就好了。
特别注意:commons-collections这个jar包要用3.x版本的,不能用4.x版本;commons-lang这个jar包要用2.x版本的,不能用3.x版本的。
我们的目的是解析下面这样的json内容:
{ "data":{ "items":[ { "itemstring":"手机", "itemcoord":{"x":0,"y":100,"width":40,"height":20}, } ], "session_id":"", }, "code":0, "message":"OK" }
代码如下:
package format; import net.sf.json.*; public class ResolveJson { public static void main(String[] args) { String json = "{\"data\":{\"items\":[{\"itemstring\":\"手机\",\"itemcoord\":{\"x\":0,\"y\":100,\"width\":40,\"height\":20},}],\"session_id\":\"\",},\"code\":0,\"message\":\"OK\"}"; JSONObject jsonObject = JSONObject.fromObject(json); JSONObject data = jsonObject.getJSONObject("data"); JSONArray items = jsonObject.getJSONObject("data").getJSONArray("items"); JSONObject row = null; for(int i=0; i<items.size(); i++){ row = items.getJSONObject(i); System.out.println("itemstring :" + row.get("itemstring")); JSONObject itemcoord = row.getJSONObject("itemcoord"); System.out.println("x:" + itemcoord.get("x")); System.out.println("y:" + itemcoord.get("y")); System.out.println("width:" + itemcoord.get("width")); System.out.println("height:" + itemcoord.get("height")); } System.out.println("session_id:" + data.get("session_id")); System.out.println("code:" + jsonObject.get("code")); System.out.println("code:" + jsonObject.get("message")); } }
运行结果:
其实解析过程就是将json看情况转换成JSONObject对象或JSONArray数组,再进行下一步处理,最终得到目的值。