java解析复杂json:JSONObject 和 JSONArray的使用

在正式解析之前,我们需要下载解析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数组,再进行下一步处理,最终得到目的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值