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?

1
  • The question seems to request a solution with Jackson. None of the answers in the possible duplicate offers a solution with Jackson specifically, Commented Feb 19, 2018 at 13:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.