JsonDocumnet replace and REST RFC

Time to give back to the community, as promised here is the code I’m using to provide a json recurisve merge like functionality.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.util.Iterator;

/**
 *
 * @author Lethe
 */
public class JsonUtil {

  public static String merge(String json, String update) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode jsonNode = mapper.readTree(json);
      JsonNode updateNode = mapper.readTree(update);
      return merge(jsonNode, updateNode).toString();
    } catch (IOException ex) {
      return null;
    }
  }

  public static JsonNode merge(JsonNode jsonNode, JsonNode updateNode) {
    Iterator<String> fieldNameIterator = updateNode.fieldNames();
    String fieldName;
    JsonNode currentNode;
    while (fieldNameIterator.hasNext()) {
      fieldName = fieldNameIterator.next();
      currentNode = jsonNode.get(fieldName);
      if (currentNode != null && currentNode.isObject()) {
        // Recursive object
        merge(currentNode, updateNode.get(fieldName));
      } else {
        if (jsonNode instanceof ObjectNode) {
          // Update field
          ((ObjectNode) jsonNode).put(fieldName, updateNode.get(fieldName));
        }
      }
    }
    return jsonNode;
  }

}

If you like I could make a pull request adding this logic in a merge method to the JsonObject class using your Jackson dependency instead, so it can be used like

JsonObject jsonObject = jsonObject1.merge(jsonObject2);

With its respective junit testing and javadoc.

2 Likes