4

I want to concatenate multiple Jackson objects. I have two String object like this

{'Key1' : 'Value1' , 'Key2' : 'Value2'}

and this

{'Key3' : 'Value3' , 'Key4' : 'Value4'}

result must be

{'Key1' : 'Value1' , 'Key2' : 'Value2' , 'Key3' : 'Value3' , 'Key4' : 'Value4'}

How can I do this in Java?

  • The question seems to request a solution with Jackson. None of the answers in the possible duplicate offers a solution with Jackson specifically, – Manos Nikolaidis Feb 19 '18 at 13:47

1 Answers1

5

This can be achieved with Jackson by parsing each String into ObjectNode (basically tree representation of the JSON) and concatenating with the setAll method. Something like this:

String json1 = "{\"Key1\": \"Value1\", \"Key2\": \"Value2\"}";
String json2 = "{\"Key3\": \"Value3\", \"Key4\": \"Value4\"}";

ObjectMapper mapper = new ObjectMapper();
ObjectNode node1 = (ObjectNode) mapper.readTree(json1);
ObjectNode node2 = (ObjectNode) mapper.readTree(json2);

JsonNode merged = node1.setAll(node2);

System.out.println(mapper.writeValueAsString(merged));

Documentation ObjectNode::setAll

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82