JsonUtils { public static void merge(JsonNode src, JsonNode target) { Iterator<Map.Entry<String, JsonNode>> fields = src.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); JsonNode subNode = entry.getValue(); switch (subNode.getNodeType()) { case OBJECT: writeObject(entry, target); break; case ARRAY: writeArray(entry, target); break; case STRING: updateObject(target, new TextNode(entry.getValue().textValue()), entry); break; case NUMBER: updateObject(target, new IntNode(entry.getValue().intValue()), entry); break; case BOOLEAN: updateObject(target, BooleanNode.valueOf(entry.getValue().booleanValue()), entry); break; default: logger.warn("Unrecognized data type {} "+subNode.getNodeType()); } } } private  JsonUtils(); static void merge(JsonNode src, JsonNode target);  }
@Test public void testMerge() { ObjectMapper mapper = new ObjectMapper(); JsonNode node1 = createJson (mapper, createJson(mapper,"numbers",Arrays.asList(1,2,3))); JsonNode node2 = createJson (mapper, createJson(mapper,"numbers",Arrays.asList(4,5,6))); JsonNode node3 = createJson (mapper, mapper.createObjectNode().put("number",1)); JsonNode node4 = createJson (mapper, mapper.createObjectNode().put("boolean",false)); JsonNode node5 = createJson (mapper, mapper.createObjectNode().put("string","javier")); JsonNode result = mapper.createObjectNode(); JsonUtils.merge(node1, result); JsonUtils.merge(node2, result); JsonUtils.merge(node3, result); JsonUtils.merge(node4, result); JsonUtils.merge(node5, result); assertEquals(1, result.size()); JsonNode merged = result.get("merged"); assertEquals(4, merged.size()); JsonNode numbers = merged.get("numbers"); assertTrue(numbers instanceof ArrayNode); ArrayNode numbersNode = (ArrayNode) numbers; assertEquals(4, numbersNode.get(0).asInt()); assertEquals(5, numbersNode.get(1).asInt()); assertEquals(6, numbersNode.get(2).asInt()); assertEquals(false, merged.get("boolean").asBoolean()); assertEquals("javier", merged.get("string").asText()); assertEquals(1, merged.get("number").asInt()); }