我有两个需要转换为JsonNode的JsonString并加入这两个JsonNode。如果两个jsonnode的键不同,代码工作正常,但如果它们相同,则后者将覆盖。 这些是我的两个JsonNodes:
" {\" PHONETYPE \":\" N95 \" \"猫\":\" WP \"}" "
{\" PHONETYPE \":\" N96 \" \"猫\":\" Wy的\&#34 ;}"
我的代码生成结果为:{"phonetype":"N96","cat":"Wy"}
public class JsonJoining {
public static void main(String[] args) throws JsonProcessingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode mainNode=mapper.readTree("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
JsonNode resuupdateNode=mapper.readTree("{\"phonetype\":\"N96\",\"cat\":\"Wy\"}");
JsonNode result=merge(mainNode, resuupdateNode);
System.out.println(result);
}
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {
Iterator<String> fieldNames = updateNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
System.out.println(fieldName);
JsonNode jsonNode = mainNode.get(fieldName);
if (jsonNode != null && jsonNode.isObject()) {
merge(jsonNode, updateNode.get(fieldName));
}
else {
if (mainNode instanceof ObjectNode) {
JsonNode value = updateNode.get(fieldName);
((ObjectNode) mainNode).put(fieldName, value);
}
}
}
return mainNode;
}
}
是否可以合并两个Jsonnode并生成第三个jsonnode,如下所示:
{"firstjson":{"phonetype":"N95","cat":"WP"},
"secondjson":{phonetype":"N96","cat":"Wy}}
答案 0 :(得分:0)
尝试以下操作:
public static JsonNode mergeCollection(JsonNode value1,JsonNode value2){
ObjectNode objectNode = mapper.createObjectNode();
if(value1!=null) {
ObjectNode node1 = mapper.createObjectNode();
node1.set("value1",value1);
node1.fields().forEachRemaining(kv -> objectNode.set(kv.getKey(), kv.getValue()));
}
if(value2!=null) {
ObjectNode node2 = mapper.createObjectNode();
node2.set("value2",value2);
node2.fields().forEachRemaining(kv -> objectNode.set(kv.getKey(), kv.getValue()));
}
return objectNode;
}
答案 1 :(得分:0)
ObjectMapper mapper = new ObjectMapper();
ArrayNode jsonArray = mapper.createArrayNode();
jsonArray.add(value1);
jsonArray.add(value2);
System.out.println(jsonArray);
答案 2 :(得分:-1)
相信我,下面的代码是合并两个或多个 jsonnodes 的最佳方式
git checkout M
git pull origin M
git checkout My
git merge M -m "local merge"