java解析多层嵌套json字符串

1. com.alibaba.fastjson

jar包地址:https://www.mvnjar.com/com.alibaba/fastjson/jar.html

2.多层解析

java分别解析下面两个json字符串

package jansonDemo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TestJSON {
    /**
     * JSON实际上也是键值对("key":"value")
     * key 必须是字符串,value 可以是合法的 JSON 数据类型(字符串, 数字, 对象, 数组, 布尔值或 null)
     * value如果是字符串,用jsonobj.getString("key")获取
     * value如果是数  字,用jsonobj.getIntValue("key"),jsonobj.getFloatValue("key"),jsonobj.getInteger("key")等基本数据类型及其包装类的方法获取
     * value如果是布尔值,用jsonobj.getBoolean("key"),jsonobj.getBooleanValue("key")获取
     * value如果是数  组,用jsonobj.getJSONArray("key")获取
     * value如果是Object对象,用jsonobj.get("key"),获取
     * value如果是JSONObject对象,用jsonobj.getJSONObject("key")获取
     */

    /**
     * 该方法用于将已有的json字符串转换为json对象,并取出该对象中相应的key对应的value值
     * 将已有的字符串转换成jsonobject,用JSON.parseObject(jsonStr)方法
     * json中只要是{}就代表一个JSONObject,[]就代表一个JSONArray
     * 获取JSONObject对象用JSONObject jsonobject.getJSONObject("key")方法
     * 获取JSONArray对象用JSONObject jsonobject.getJSONArray("key")方法
     */

    private static void strWritedToJSONObject() {
        //以下是一个json对象中嵌套一个json子对象
        String myJsonObj = "{
" +
                "    "name":"runoob",
" +
                "    "alexa":10000,
" +
                "    "sites": {
" +
                "        "site1":"www.runoob.com",
" +
                "        "site2":"m.runoob.com",
" +
                "        "site3":"c.runoob.com"
" +
                "    }
" +
                "}";
        JSONObject jsonobj = JSON.parseObject(myJsonObj); //将json字符串转换成jsonObject对象
        /***获取JSONObject中每个key对应的value值时,可以根据实际场景中想得到什么类型就分别运用不到的方法***/
        System.out.println(jsonobj.get("name")); //取出name对应的value值,得到的是一个object
        System.out.println(jsonobj.getString("name")); //取出name对应的value值,得到的是一个String
        System.out.println(jsonobj.getIntValue("alexa")); //取出name对应的value值,得到的是一个int
        System.out.println(jsonobj.get("sites")); //取出sites对应的value值,得到的是一个object
        System.out.println(jsonobj.getString("sites"));
        System.out.println(jsonobj.getJSONObject("sites")); //取出sites对应的value值,得到一个JSONObject子对象
        System.out.println(jsonobj.getJSONObject("sites").getString("site2")); //取出嵌套的JSONObject子对象中site2对应的value值,必须用getJSONObject()先获取JSONObject


        /**
         * 以下是一个json对象中包含数组,数组中又包含json子对象和子数组
         */
        String myJsonObj2 = "{
" +
                "    "name":"网站",
" +
                "    "num":3,
" +
                "    "sites": [
" +
                "        { "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻译" ] },
" +
                "        { "name":"Runoob", "info":[ "菜鸟教程", "菜鸟工具", "菜鸟微信" ] },
" +
                "        { "name":"Taobao", "info":[ "淘宝", "网购" ] }
" +
                "    ]
" +
                "}";
        JSONObject jsonobj2 = JSON.parseObject(myJsonObj2); //将json字符串转换成jsonObject对象
        System.out.println(jsonobj2.get("sites"));
        System.out.println(jsonobj2.getString("sites"));
        System.out.println(jsonobj2.getJSONArray("sites")); //取出sites对应的value值,得到一个JSONOArray对象
        //System.out.println(jsonobj2.getJSONObject("sites")); 不能用该方法,因为sites是一个JSONOArray对象
        //取出json对象中sites对应数组中第一个json子对象的值
        System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0)); //得到结果:{"name":"Google","info":["Android","Google 搜索","Google 翻译"]}
        System.out.println(jsonobj2.getJSONArray("sites").get(0));
        System.out.println(jsonobj2.getJSONArray("sites").getString(0));
        //取出json对象中sites对应数组中第一个json子对象下面info对应的嵌套子数组值
        System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0).getJSONArray("info")); //得到结果:["Android","Google 搜索","Google 翻译"]
        //取出json对象中sites对应数组中第一个json子对象下面info对应的嵌套子数组中第二个值
        System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0).getJSONArray("info").getString(1)); //得到结果:Google 搜索

        //依次取出json对象中sites对应数组中的值
        JSONArray array = jsonobj2.getJSONArray("sites");
        getJsonArrayItem(array);
        //依次取出json对象中sites对应数组中第二个json子对象下面info对应的嵌套子数组值
        JSONArray arr = jsonobj2.getJSONArray("sites").getJSONObject(1).getJSONArray("info");
        getJsonArrayItem(arr);
     }

    /**
     * 手动添加对象到一个JSONObject
     */
    private static void writeStrToJSONObject() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","tom");
        jsonObject.put("age",20);

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonArrayObject1 = new JSONObject();
        jsonArrayObject1.put("name","alibaba");
        jsonArrayObject1.put("info","www.alibaba.com");
        JSONObject jsonArrayObject2 = new JSONObject();
        jsonArrayObject2.put("name","baidu");
        jsonArrayObject2.put("info","www.baidu.com");

        jsonArray.add(jsonArrayObject1);
        jsonArray.add(jsonArrayObject2);

        jsonObject.put("sites",jsonArray);

        System.out.println(jsonObject);
     }

    /**
     * 将字符串转为JSONArray
     */
    private static void strToJsonArray() {
        String arrayStr = "[
" +
                "        {
" +
                "            "name":"alibaba",
" +
                "            "info":"www.alibaba.com"
" +
                "        },
" +
                "        {
" +
                "            "name":"baidu",
" +
                "            "info":"www.baidu.com"
" +
                "        }
" +
                "    ]";

        JSONArray array = JSON.parseArray(arrayStr);
        System.out.println(array);
     }

    /**
     * 依次取出JSONArray中的值
     */
    private static void getJsonArrayItem(JSONArray array) {
        for (int i=0; i<array.size(); i++) {
            System.out.println(array.get(i));
        }
    }

     //测试类
    public static void main(String[] args) {
        strWritedToJSONObject();
        //writeStrToJSONObject();
        //strToJsonArray();
    }

}

小结:如果是{ } 用 getJSONObject   [ ] 用 getJSONArray

JSONArray内的{ },用for循环遍历:

 String s = "[{"success":true,"data":[{"building_id":"***","building_num":"**","room_name":"**","door_name":"**","electric":"**"}]}]";

 JSONArray ja = jsonx.getJSONArray("data");
        for (int i = 0; i < ja.size(); i++) {
            JSONObject jo = ja.getJSONObject(i);
            String building_id = jo.getString("building_id");
        }

3.JsonObject判断一个json串中是否含有某个key值

public static void main(String[] args) throws JSONException {

  String jsonStr = "{'content':['','','',''],'Baseline':{'content':['1','2'],'BaselineName':'JC','BaselineId':'813xxx'}}";

  JSONObject jsonObject = new JSONObject(jsonStr);

  //这里调用JSONObject 的has方法来判断一个key值是否存在,如果存在返回true

  if(jsonObject .has("Baseline")){

    //这里对应当前key值存在后的操作

    JSONObject jsonObject2 = (JSONObject)jsonObject.get("Baseline");

    ......

    ......

  }

}

4.fastjson如何判断JSONObject和JSONArray

 /**
     * 单层的orgJson判断是否是JSONObject还是JSONArray.
     */
    public static void simpleJSONObjectOrgJson() {
        String message = "[{
" + "        "DataSource": "'P33'",
"
                + "        "DataStamp": "'2018-08-25'",
" + "        "GovScCode": "'aaa'",
"
                + "        "OperEffDate": "'2018-05-02'",
" + "        "OrgCode": "'ww'",
"
                + "        "OrgDesc": "'ss'",
" + "        "OrgId": "1",
"
                + "        "OrgName": "'11111'",
" + "        "OrgSeq": "11",
"
                + "        "OrgShortName": "'ss'",
" + "        "OrgStatus": "'ss'",
"
                + "        "OrgType": "'ss'",
" + "        "ParentOrgId": "0",
"
                + "        "RegAddress": "'ww'",
" + "        "RegDate": "",
" + "        "RegionId": "1"
"
                + "    }]";
        Object json = new JSONTokener(message).nextValue();
        if (json instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) json;
            System.out.println(jsonObject);
            //自行解析即可
        } else if (json instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) json;
            System.out.println(jsonArray);
            //自行解析即可
        }
    }

 以上是此次项目遇到的问题,感谢以下大佬分享:

https://www.cnblogs.com/janson071/p/9646678.html

https://blog.csdn.net/kxj19980524/article/details/83718971

https://www.cnblogs.com/1012hq/p/11141932.html

https://www.cnblogs.com/biehongli/p/9721846.html

原文地址:https://www.cnblogs.com/SI0301/p/11277109.html