Java traversing Json data

Today, we need to traverse json, but only one level of traversal is found, which is not enough for multi-level json traversal. So write it yourself, and use fastJson to handle it.

When traversing json, we need to consider multi-level json. We need to consider JSONObject and JSONArray. We need to deal with these two situations. We use recursion to traverse down, use instanceof to judge the type of recursion, and do different processing. Code below:

public class JsonLoop {

    public static String json = "{\"TITLE\":\"Json Title\",\"FORM\":{\"USERNAME\":\"Rick and Morty\"},\"ARRAY\":[{\"FIRST\":\"Rick\"},{\"LAST\":\"Morty\"}]}";

    public static void jsonLoop(Object object) {

        if(object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
                Object o = entry.getValue();
                if(o instanceof String) {
                    System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
                } else {
                    jsonLoop(o);
                }
            }
        }
        if(object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            for(int i = 0; i < jsonArray.size(); i ++) {
                jsonLoop(jsonArray.get(i));
            }
        }
    }

    public static void main(String[] args) {

        JSONObject jsonObject = JSON.parseObject(json);
        jsonLoop(jsonObject);
    }
}

Traversal is as follows, including json data of JSONObject and JSONArray:

{
    "TITLE":"Json Title",
    "FORM":{
        "USERNAME":"Rick and Morty"
    },
    "ARRAY":[
        {
            "FIRST":"Rick"
        },
        {
            "LAST":"Morty"
        }
    ]
}

Below is the output:

key:FIRST,value:Rick
key:LAST,value:Morty
key:USERNAME,value:Rick and Morty
key:TITLE,value:Json Title

Tags: JSON

Posted on Fri, 08 Nov 2019 13:01:45 -0500 by dscapuano