将多个字符串json合并到一个Java中

时间:2019-10-14 13:08:03

标签: java json

我有多个json字符串,例如:

JSON 1:

{
"a":"test1",

"b":"test2"
}

JSON 2:

{
"b":"test3",

"c":"test4"
}

我希望最终的json为:

{
"a":"test1",

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

如何在Java中做到这一点?

3 个答案:

答案 0 :(得分:0)

您需要使用API​​或框架来解析Java中的JSON。然后,您必须遍历JSON字符串,将其解析为键值对。一旦有了这些,我建议使用Map按密钥存储它们。这是一些伪代码:

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

答案 1 :(得分:0)

您可以使用JSONObject class进行所需的操作。据我了解,您当前有一些字符串。您可以使用构造函数为每个String创建一个JSONObject:

JSONObject jObject = new JSONObject(String str);

然后,您可以遍历JSONObject,检查所有内容以构造新JSONObject中的新JSON。您有一些非常好的方法可能对您非常有用,但是我认为get和put方法足以实现此合并。

答案 2 :(得分:0)

您可以使用任何一种最受欢迎​​的JSON库来实现此目的,以下示例显示了如何通过Jackson将多个JSON字符串合并为一个。

对于合并的JSON字符串,我使用Map<String, Object>(例如 jsonMap )。如果所有给定JSON字符串中的键均相同,则其在 jsonMap 中的值将为String。否则,其值为List<String>

示例代码

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());

控制台输出

  

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