如果我们给了2个类型为json的字符串,我们如何将它们合并到java中的单个json String中?
e.g.
String json1 = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S"
}
}
}
String json2 = {
"glossary": {
"title": "person name",
"age": "25"
}
}
应该产生
String mergedJson = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S"
},
"age": "25"
}
}
答案 0 :(得分:6)
下面的代码应该做,有几个假设:
com.fasterxml.jackson.databind.ObjectMapper
)来序列化/反序列化json json1的字段在合并时将始终覆盖json2
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map1 = mapper.readValue("json1", Map.class);
Map<String, Object> map2 = mapper.readValue("json2", Map.class);
Map<String, Object> merged = new HashMap<String, Object>(map2);
merged.putAll(map1);
System.out.println(mapper.writeValueAsString(merged));
答案 1 :(得分:1)
这是递归合并两个jsons的代码。这输出为例外:
private static JsonObject merge(JsonObject json1Obj, JsonObject json2Obj) {
Set<Entry<String, JsonElement>> entrySet1 = json1Obj.entrySet();
for (Entry<String, JsonElement> entry : entrySet1) {
String key1 = entry.getKey();
if (json2Obj.get(key1) != null) {
JsonElement tempEle2 = json2Obj.get(key1);
JsonElement tempEle1 = entry.getValue();
if (tempEle2.isJsonObject() && tempEle1.isJsonObject()) {
JsonObject mergedObj = merge(tempEle1.getAsJsonObject(),
tempEle2.getAsJsonObject());
entry.setValue(mergedObj);
}
}
}
Set<Entry<String, JsonElement>> entrySet2 = json2Obj.entrySet();
for (Entry<String, JsonElement> entry : entrySet2) {
String key2 = entry.getKey();
if (json1Obj.get(key2) == null) {
json1Obj.add(key2, entry.getValue());
}
}
return json1Obj;
}
答案 2 :(得分:0)
所以我参加聚会很晚,但是如果有人偶然发现,我想分享我的解决方案。
您可以将两个json字符串与com.fasterxml.jackson.core:jackson-databind
ObjectMapper.readerForUpdating()
进行深度合并。
在这种情况下,您将两个Json作为String传入,并通过readerForUpdating(未经测试的代码)合并它们:
public String mergeJsonStrings(String json1, String json2) {
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerForUpdating(json1);
String result = reader.readValue(json2);
return result;
}
我使用类似的代码将属性合并到现有数据集中。在此示例中,SomeProperties
类包含一个哈希图,该哈希图保存特定用户的属性。传入的propertiesString
是单点分隔的属性,例如some.random.property=value
。该属性将通过JsonNode
转换为com.fasterxml.jackson.dataformat:jackson-dataformat-properties
。
public SomeProperties mergeProperties(SomeProperties someProperties, String propertiesString) {
JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = javaPropsMapper.readTree(propertiesString);
ObjectReader objectReader = mapper.readerForUpdating(someProperties.getProperties());
HashMap<String, Object> mergedProperties = objectReader.readValue(jsonNode);
someProperties.setProperties(mergedProperties);
return someProperties;
}
在两种情况下,传递给objectReader.readValue()
的所有内容都会覆盖现有键。