Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Two JSON Documents Using Jackson

Tags:

java

json

jackson

Is it possible to merge two JSON documents with the Jackson JSON library? I am basically using the Jackson mapper with simple Java Maps.

I've tried to search in Google and Jackson's documentation but couldn't find anything.

like image 356
Danish Avatar asked Mar 27 '12 18:03

Danish


People also ask

How does Jackson read nested JSON?

A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.

How does Jackson parse JSON?

databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.

How do I combine two JSON arrays?

We can merge two JSON arrays using the addAll() method (inherited from interface java.


1 Answers

Inspired by StaxMans answer I implemented this merging method.

public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {      Iterator<String> fieldNames = updateNode.fieldNames();     while (fieldNames.hasNext()) {          String fieldName = fieldNames.next();         JsonNode jsonNode = mainNode.get(fieldName);         // if field exists and is an embedded object         if (jsonNode != null && jsonNode.isObject()) {             merge(jsonNode, updateNode.get(fieldName));         }         else {             if (mainNode instanceof ObjectNode) {                 // Overwrite field                 JsonNode value = updateNode.get(fieldName);                 ((ObjectNode) mainNode).put(fieldName, value);             }         }      }      return mainNode; } 

Hope this helps someone.

like image 138
Arne Avatar answered Sep 20 '22 15:09

Arne