Home > Enterprise >  How to merge two JSON string
How to merge two JSON string

Time:05-17

I have two JSON strings, I want to merge these two response string into a single one. Is there any way to merge these two JSON string using java ?

String str1 = "{
                "data" : { 
                        "values" : {
                            "name" : "kiran",
                            "age"  : "24"
                        }
                        }
                        }"
                        
String str2 = "{
                "data" : { 
                        "values" : {
                            "name" : "Mamu",
                            "age"  : "26"
                        }
                        }
                        }"

I wnat to merge these two JSON string as follows

String mergeResult = "{
                "data" : { 
                        "values" : [
                        {
                            "name" : "kiran",
                            "age"  : "24"
                        },
                        {
                            "name" : "Manu",
                            "age"  : "26"
                        }
                        ]
                        }
                        }"

CodePudding user response:

From your example JSON it looks like there can be many more input objects than two, so I'd use a JSON to JSON transform via JOLT library (https://github.com/bazaarvoice/jolt) as follows:

  1. Form a JSON array of all the input {"data" : ...} objects (either by collecting the original objects and putting them in a List before serialization or just manually by concatenating their JSONs with square brackets):
[
  {
    "data": {
      "values": {
        "name": "kiran",
        "age": "24"
      }
    }
  },
  {
    "data": {
      "values": {
        "name": "Mamu",
        "age": "26"
      }
    }
  }
]
  1. Use the JOLT spec:
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "data": {
          "values": {
            "@": "data.values[]"
          }
        }
      }
    }
  }
]

The resulting JSON:

{
  "data" : {
    "values" : [ {
      "name" : "kiran",
      "age" : "24"
    }, {
      "name" : "Mamu",
      "age" : "26"
    } ]
  }
}

You can test or modify the spec yourself at http://jolt-demo.appspot.com before using it in your application.

Here's what Java side might look like:

Resource transformationSpec = ...
String inputJson = ...
List<Object> specs = JsonUtils.jsonToList(transformationSpec.getInputStream());
Chainr chainr = Chainr.fromSpec(specs);
Object inputObject = JsonUtils.jsonToObject(inputJson);
Object transformedObject = chainr.transform(inputObject);
String transformedJson = JsonUtils.toJsonString(transformedObject);

CodePudding user response:

May be not the most efficient solution but very simple one would be to parse each String into a Map (or specific POJO if you have one) and merge them as maps, and than serialize back into Json String. To parse a json string to map or a specific POJO you can use Jackson library - method readValue() of ObjectMapper Or Gson library. Also, I wrote my own simple wrapper over Jackson library that simplifies the use. Class JsonUtils is available as part of MgntUtils library (written and maintained by me). This class just has the methods that allow you to parse and de-serialize from/to Json String from/to a class instance. So your code could be as follows:

public String mergeJsonStrings(String str1, Str2) throws IOException {
  Map<String, Object> map1 = convertJsonStringToMap(str1);
  Map<String, Object> map2 = convertJsonStringToMap(str2);
  Map<String, Object> dataMap1 = (Map<String, Object>)map1.get("data");
  Map<String, Object> valuesMap1 = (Map<String, Object>)dataMap1.get("values");
  Map<String, Object> dataMap2 = (Map<String, Object>)map2.get("data");
  Map<String, Object> valuesMap2 = (Map<String, Object>)dataMap2.get("values");
  valuesMap1.putAll(valuesMap2);
  return convertMapToJsonString(map1);
}


  Map<String, Object> convertJsonStringToMap(String str) throws IOException {
    return JsonUtils.readObjectFromJsonString(str, Map.class);
  }

  Strong convertMapToJsonString(Map<String,Object> map) throws JsonProcessingException{
    return JsonUtils.writeObjectToJsonString(map); 
  }

This example uses MgntUtils library to parse and serialize JSON but of course you can use Jackson, Gson or any other library you want. MgntUtils library available as Maven artifact and on Github (including source code and Javadoc)

  • Related