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数组,再进行下一步处理,最终得到目的值。

  • 相关阅读:
    逆光拍摄常见的问题(解决大光比问题)
    HDP和包围曝光
    直方图
    linux查找文件的命令【转】
    100篇大数据文章[转]
    squid
    修改/etc/resolv.conf又恢复到原来的状态?[转]
    python字符串及正则表达式[转]
    GraphLab介绍[转]
    Scala 中的 apply 和 update 方法[转]
  • 原文地址:https://www.cnblogs.com/firstdream/p/10069673.html
Copyright © 2011-2022 走看看