Read hashmap nested properties dynamically

Tags:



I have the JSON below:

"total":"2",
"offset":"1",
"limit":"2",
"results":[{    
    "code":1,
    "title":"RESTAURANTE SADOCHE",
    "contact":{
        "code":10,
        "name":"HENRIQUE BARBALHO",
        "company":{
            "code":100,
            "name":"RESTAURANTE SADOCHE LTDA-ME"
        }
    }
},
{
    "code":2,
    "title":"ARNALDO GRILL",
    "contact":{
        "code":20,
        "name":"FÁTIMA COSTA",
        "company":{
            "code":200,
            "name":"COSTA NATAL RESTAURANTE EIRELI"
        }
    }
}]

I turned this JSON into a Java HashMap using the Gson library.

Map<String, Object> retMap = new Gson().fromJson(jsonUpString, new TypeToken<HashMap<String, Object>>(){}.getType());

I need to dynamically read some properties of this created hashmap. Ex: title, name of contact and name of company.

Sometimes these properties (title, name of contact and name of company) can be inside lists.

Below my code:

String propertyName = "name";
String nesting = "results;contact;company";
String[] levels = nesting.split(";");

Map map = new HashMap();
map = retMap;

for (int i = 0; i < niveis.length; i++) {                        
    map = (Map)map.get(levels[i]);        
    System.out.println(map);

    if (i == levels.length - 1) {
        System.out.println(map.get(propertyName));
    }
}

But if the properties (results, contact or company) return more than one object, the JSON returns them as lists, and I can’t get the information I need.

Answer

I solved the problem using…

private static void leJSON(Object object) {
    if (object instanceof JSONObject) {
        Set < String > ks = ((JSONObject) object).keySet();
        for (String key: ks) {
            Object value = ((JSONObject) object).get(key);
            if (value != null) {
                System.out.printf("%s=%s (%s)n", key, value, value.getClass().getSimpleName());
                if (value.getClass().getSimpleName().equalsIgnoreCase("JSONArray")) {
                    JSONArray ja = (JSONArray) value;
                    for (int i = 0; i < ja.size(); i++) {
                        leJSON(ja.get(i));
                    }
                }
                if (value.getClass().getSimpleName().equalsIgnoreCase("JSONObject")) {
                    leJSON(value);
                }
            }
        }
    }
}

main method…

String json = "{...}";
JSONObject object = (JSONObject) JSONValue.parse(jsonString2);        
readJSON(object);


Source: stackoverflow