Java:合并两个JSON对象而不进行迭代

时间:2018-10-17 03:56:44

标签: java json

我有两个JSON对象,例如

{  
   "key1":"value1",
   "key2":"value2",
   "key3":"value3",
   "key4":"value4"
}

{
   "key2":"value1",
   "key4":"value2",
   "key6":"value3",
   "key8":"value4"
}

我想将这两个JSON对象合并为单个Json对象,而无需遍历每个键,最终结果应为

{
   "key1":"value1",
   "key2":"value1",
   "key3":"value3",
   "key4":"value2",
   "key6":"value3",
   "key8":"value4"
}

1 个答案:

答案 0 :(得分:2)

使用任何Json Mapper(例如Jackson)将json转换为Map。

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String, String>>(){})

一旦获得了两个这样的地图,就可以将它们合并

Map<String, Object> mergedMap = new HashMap<>();
mergedMap.putAll(map1);
mergedMap.putAll(map2);
String json = mapper.writeValueAsString(mergedMap);