zoukankan      html  css  js  c++  java
  • 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数组,再进行下一步处理,最终得到目的值。

  • 相关阅读:
    猴面包树果 baobab tree
    关于 韩国 申明 豆浆 和 端午 是其国家创造或历史的 看法
    初中英语课本里隐藏着的惊人秘密(转载)
    如果不出意外,我每周都会去工大打球
    新开始做wpf,随便写点经验
    当你老了 叶芝
    继承Form中的DevExpress控件不能打开编辑器Designer
    骑 自行车 从公司 到家
    LJP Little John PalmOS 1.0 Release 最新版 (RC9后的正式版)
    我的语文备忘
  • 原文地址:https://www.cnblogs.com/firstdream/p/10069673.html
Copyright © 2011-2022 走看看