Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two json Strings into one in java

Tags:

java

json

If we have given 2 Strings of type json, how can we merge them into single json String in java?

e.g. 

    String json1 = {
        "glossary": {
            "title": "example glossary",
            "GlossDiv": {
                "title": "S"
            }
        }
    }

String json2 = {
        "glossary": {
            "title": "person name",
            "age":  "25"
        }
    }  

Should produce

String mergedJson = {
   "glossary": {
            "title": "example glossary",
            "GlossDiv": {
                "title": "S"
            },
            "age":  "25"
        }
}
like image 757
Prashant Thorat Avatar asked Jan 07 '23 13:01

Prashant Thorat


1 Answers

Below code should do it, with a couple of assumptions:

  • You are using ObjectMapper of Jackson library (com.fasterxml.jackson.databind.ObjectMapper) to serialise/deserialise json
  • fields of json1 will always overwrite json2 while merging

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map1 = mapper.readValue("json1", Map.class);
    Map<String, Object> map2 = mapper.readValue("json2", Map.class);
    Map<String, Object> merged = new HashMap<String, Object>(map2);
    merged.putAll(map1);
    System.out.println(mapper.writeValueAsString(merged));
    
like image 189
Darshan Mehta Avatar answered Jan 14 '23 17:01

Darshan Mehta