0

I have multiple json strings like:

JSON 1:

{
"a":"test1",

"b":"test2"
}

JSON 2:

{
"b":"test3",

"c":"test4"
}

I want final json as:

{
"a":"test1",

"b":["test2","test3"],
"c":"test4"
}

How can I do this in java?

TheWhiteRabbit
  • 1,253
  • 1
  • 5
  • 18
  • What's the business here? Why b has test2 and then becomes test1, test3? why JSON 1 is declared twice? Please update your question, and explain what you want in english not in Json :) – Ioannis Barakos Oct 14 '19 at 13:11
  • check this https://stackoverflow.com/questions/58261053/how-to-get-all-the-distinct-values-by-key-inside-stream-java8/58261339#58261339 this will give u some hints – pvpkiran Oct 14 '19 at 13:23
  • you seems to need a different behaviour for values creation, i,e if it's the only value use `String` type else use `List`, you'll need to parse the json to objects and then build the result json, merge by custom logic... – shahaf Oct 14 '19 at 13:41

3 Answers3

0

You'll need an API or framework for parsing JSON in java. Then you'll have to iterate over your JSON strings, parse them into key value pairs. Once you have that, I recommend using a Map to store them by key. Here is some Pseudo Code:

public class KeyValuePair {
    private String key = null;
    private String value = null;
    // todo create constructor with arguments
    // todo create getters and setters
}

private List<KeyValuePair> parseJSON(String json) {
    List<KeyValuePair> parsed = new ArrayList<>();
    // todo use the JSON API you chose to parse the json string into an ArrayList of KeyValuePair
    return parsed;
}

Map<String, List<String>> results = new HashMap<>();
List<String> jsonStrings = new ArrayList<>();
// todo read your JSON strings into jsonStrings
for (String jsonString : jsonStrings) {
    List<KeyValuePair> pairs = parseJSON(jsonString);
    for (KeyValuePair pair : pairs) {
        List<String> values = results.get(pair.getKey());
        if (values == null) {
            values = new ArrayList<>();
            results.put(pair.getKey(), values);
        }
        values.add(pair.getValue());
    }
}
// todo you'll have to loop through the map's keys and construct your result JSON
bcr666
  • 2,157
  • 1
  • 12
  • 23
0

You can use the JSONObject class to do the operations you need. As I understand you are currently having some Strings. You can create a JSONObject for each of your String using the constructor :

JSONObject jObject = new JSONObject(String str);

Then you can iterate through your JSONObject, do all your checking an construct the new JSON inside a new JSONObject. You have some really nice methods that can be very helfpful for you, but I think the get and put methods would be enough to achieve this merge.

Andrei Tigau
  • 2,010
  • 1
  • 6
  • 17
0

You can use any one of the most popular JSON libraries to achieve this, following sample shows how to merge several JSON string into one by Jackson.

I use a Map<String, Object> (says jsonMap) for the merged JSON string. If the key in all given JSON string is identical, then its value in jsonMap will be String. Otherwise, its value will be List<String>.

Sample code

List<String> jsonStrList = Arrays.asList("{\"a\":\"test1\",\"b\":\"test2\"}","{\"b\":\"test3\",\"c\":\"test4\"}");

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> jsonMap = new HashMap<>();
for (String jsonStr : jsonStrList) {
    Map<String, String> jsonContent = mapper.readValue(jsonStr, Map.class);
    jsonContent.forEach((k,v) -> {
        if (jsonMap.containsKey(k)) {
            if (jsonMap.get(k) instanceof String) {
                List<String> content = new ArrayList<>();
                content.add(jsonMap.get(k).toString());
                content.add(v);
                jsonMap.put(k, content);
            } else {
                jsonMap.put(k, ((ArrayList) jsonMap.get(k)).add(v));
            }
        } else {
            jsonMap.put(k, v);
        }
    });
}
System.out.println(jsonMap.toString());
System.out.println(new ObjectMapper().writeValueAsString(jsonMap).toString());

Console output

{a=test1, b=[test2], c=test4}
{"a":"test1","b":["test2","test3"],"c":"test4"}

LHCHIN
  • 3,679
  • 2
  • 16
  • 34