Convert Json string into Hashmap of hashmap in java

200 Views Asked by At

I am new to json processing, below is the json string our clients send us, I want to read this json string into a hashmap of hasmap so that even for the "Client"/"params" key below I can access its key and value set and process them .

var incomingMessage = 

"{  
    \"dev1\":\"NULL\",  
    \"devkp2\":\"val\",     
    \"compression\":\"NULL\",
    \"subcode\":\"P_CODE\",
    \"code\":\"PEB_USER\",
    \"Client\":{
                \"first_name\":\"Perf FN 422677\",
                \"client_last_name\":\"DP_PSL\",
                \"clientid\":\"780A832\",
                \"email\":\"[email protected]\"
                },
    \"clientsrc\":\"dev.client.notvalid\",
    \"params\":{
                \"Name\":\"ABC_PR\",
                \"client_ID\":\"PSL\",
                \"domain\":\"airb.com\"
                }
}"

This is my current code which works fine for non-nested json strings (that is without the Client.params key in above json string):

public static void convertJsonStringToMap(String incomingMessage) {

    HashMap<Object, Object> map = new HashMap<Object, Object>();
    JSONObject jObject = new JSONObject(incomingMessage);
    Iterator<?> keys = jObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        String value = jObject.getString(key);
        map.put(key, value);

    }
    for (Map.Entry<Object, Object> entry : map.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

    }
}

I want to be able to similarly read nested keys like Client and params. I am using jdk11. I am fine with using jackson or google gson, both approaches would work.

Please help me with processing these nested json string.

1

There are 1 best solutions below

0
On

A valid JSON string can be easily converted to a Map using Jackson ObjectMapper.

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsedMap = mapper.readValue(incomingMessage, Map.class);

It works for nested elements as well -

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String someJsonString = "{" +
            "\"A\":\"1\"," +
            "\"B\":2," +
            "\"C\":" +
                "{" +
                "\"D\":\"4\"" +
                "}" +
            "}";

    Map<String, Object> outputMap = mapper.readValue(someJsonString, Map.class);
    System.out.println(outputMap);
}

Output:

{A=1, B=2, C={D=4}}