Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the keys of json in java using Gson or org.json library? [duplicate]

Tags:

java

json

For example from the following json, id, items, fromNumber should be retrieved. The json can be having n number of nesting.

{
"items": [{
    "id": 633706061003,
    "fromNumber": "16572307534",

    "contact": {
        "id": 499354453003,
        "homePhone": "16572307534"
    },

    "records": [{
        "id": 353389055003,
        "result": "LA",
        "recordings": [{
            "id": 16427622003,
        }]
    }]
}],
"limit": 100,
"offset": 0,
"totalCount": 5949

}

I have implemented the below code, but in this code I have to tell the level of nesting

String prefix = "";

    /*
     * Root Array
     */
    JsonArray rootArray = new JsonParser().parse(json).getAsJsonArray();

    for (int i = 0; i < rootArray.size(); i++) {

        /*
         * Single object in root array while iterations. for id, properties, tags etc.
         */
        JsonObject rootArrayObject = rootArray.get(i).getAsJsonObject();

        Set<Map.Entry<String, JsonElement>> rootArrayObjectEntrySet = rootArrayObject.entrySet();

        /*
         * Getting the keys and values of RootArray Single Object
         */
        for (Map.Entry<String, JsonElement> entryChild : rootArrayObjectEntrySet) {

            prefix = entryChild.getKey();

            /*
             * Getting each object, key or array as an element
             */
            JsonElement rootArrayObjElement = rootArrayObject.get(entryChild.getKey());


            if(rootArrayObjElement.isJsonArray()){

                /*
                 * Getting array's object in single object of root array. Example: tags
                 */
                JsonArray rootArrayObjArray = rootArrayObjElement.getAsJsonArray();

                for (int j = 0; j < rootArrayObjArray.size(); j++) {


                }


            }else if(rootArrayObjElement.isJsonObject()){

                /*
                 * Single object in root array 
                 */
                JsonObject rootArrayObjObj = rootArrayObjElement.getAsJsonObject();

                Set<Map.Entry<String, JsonElement>> rootArrayObjObjEntrySet = rootArrayObjObj.entrySet();

                for (Map.Entry<String, JsonElement> rootArrayObjObjChild : rootArrayObjObjEntrySet) {




                    /*
                     * Getting each object, key or array as an element
                     */
                    JsonElement rootArrayObjObjElement = rootArrayObjObj.get(rootArrayObjObjChild.getKey());

                    if(rootArrayObjObjElement.isJsonPrimitive()){




                    }else if(rootArrayObjObjElement.isJsonArray()){

                        JsonArray rootArrayObjArray = rootArrayObjObjElement.getAsJsonArray();

                        for (int j = 0; j < rootArrayObjArray.size(); j++) {



                        }
                    }

                }


            }else if(rootArrayObjElement.isJsonPrimitive()){




            }


        }





    }
like image 407
Angie Russell Avatar asked Oct 22 '25 22:10

Angie Russell


2 Answers

You can try something like below :

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;


public class GSonWay {

    public static void main(String[] args) throws Exception {
        String jsonString = "{\n"
                + "\"items\": [{\n"
                + "    \"id\": 633706061003,\n"
                + "    \"fromNumber\": \"16572307534\",\n"
                + "\n"
                + "    \"contact\": {\n"
                + "        \"id\": 499354453003,\n"
                + "        \"homePhone\": \"16572307534\"\n"
                + "    },\n"
                + "\n"
                + "    \"records\": [{\n"
                + "        \"id\": 353389055003,\n"
                + "        \"result\": \"LA\",\n"
                + "        \"recordings\": [{\n"
                + "            \"id\": 16427622003\n"
                + "        }]\n"
                + "    }]\n"
                + "}],\n"
                + "\"limit\": 100,\n"
                + "\"offset\": 0,\n"
                + "\"totalCount\": 5949\n"
                + "\n"
                + "}";
        List keys1 = getKeysFromJson(jsonString);
        System.out.println(keys1.size());
        System.out.println(keys1);

    }

    static List getKeysFromJson(String jsoString) throws Exception {
        Object things = new Gson().fromJson(jsoString, Object.class);
        List keys = new ArrayList();
        collectAllTheKeys(keys, things);
        return keys;
    }

    static void collectAllTheKeys(List keys, Object o) {
        Collection values = null;
        if (o instanceof Map) {
            Map map = (Map) o;
            keys.addAll(map.keySet()); // collect keys at current level in hierarchy
            values = map.values();
        } else if (o instanceof Collection) {
            values = (Collection) o;
        } else{return;}

        for (Object value : values) {
            collectAllTheKeys(keys, value);
        }
    }
}

Output :

[items, limit, offset, totalCount, id, fromNumber, contact, records, id, homePhone, id, result, recordings, id]
like image 133
Madushan Perera Avatar answered Oct 25 '25 10:10

Madushan Perera


Gson is one of the best ways to decode JSON file. Gson requires POJO classes, which can be manually generated but is tiresome. The best way to develop POJO classes is to visit jsonschema2pojo.org. They will generate the required POJO classes for you.

Let's say the class is JsonData.java

So in your code, you have to create a Gson object as well as an object of JsonData class.

String jsonFile = "____let this be your json data___"

Gson gson = new Gson();
JsonData jsonData = new JsonData();
jsonData = gson.fromJson(jsonFile, JsonData.class);

now jsonData will have all the data's retrieved from the json file. If you want to get fromNumber you can just call getFromNumber() which will be a method inside JsonData class. Similarly you can call other values too.

Try using third party services like jsonschema2pojo.org for improving your productivity.

like image 45
capt.swag Avatar answered Oct 25 '25 10:10

capt.swag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!