我有多个 json 字符串,例如:
JSON 1:
{
"a":"test1",
"b":"test2"
}
JSON 2:
{
"b":"test3",
"c":"test4"
}
我想要最终的 json 为:
{
"a":"test1",
"b":["test2","test3"],
"c":"test4"
}
我怎样才能在java中做到这一点?
最佳答案
您可以使用任何一种最流行的 JSON 库来实现这一目标,以下示例展示了如何通过 Jackson
将多个 JSON 字符串合并为一个字符串。 。
我使用Map<String, Object>
(表示jsonMap)用于合并的 JSON 字符串。如果所有给定 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"}
关于java - 将多个字符串json合并到一个java中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58377542/