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"
        }
}
                Below code should do it, with a couple of assumptions:
com.fasterxml.jackson.databind.ObjectMapper) to serialise/deserialise jsonfields 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With