flipkart-incubator / zjsonpatch

This is an implementation of RFC 6902 JSON Patch written in Java
Apache License 2.0
527 stars 152 forks source link

JsonDiff doesn't support generating difference for binary nodes #143

Open jielearning opened 2 years ago

jielearning commented 2 years ago

Hi, it looks like JsonDiff doesn't support generating difference for binary nodes, NullPointerException with unhandled token type VALUE_EMBEDDED_OBJECT will be thrown in such situation. Is it possible to add support to generate difference for binary nodes? Thanks.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.flipkart.zjsonpatch.JsonDiff;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;

class Item {
    public ByteBuffer binaryVal;

    public Item(ByteBuffer binaryVal) {
      this.binaryVal = binaryVal;
    }
}

class Main {
  public static void main(String[] args) {
    Item firstItem = new Item(ByteBuffer.wrap("ItemOne".getBytes(StandardCharsets.UTF_8)));
    Item secondItem = new Item(ByteBuffer.wrap("ItemTwo".getBytes(StandardCharsets.UTF_8)));

    ObjectMapper mapper = new ObjectMapper();

    JsonNode firstNode = mapper.valueToTree(firstItem);
    JsonNode secondNode = mapper.valueToTree(secondItem);

    printNodeInfo(firstNode);

    JsonDiff.asJson(firstNode, secondNode);
  }

  private static void printNodeInfo(JsonNode jsonNode) {
    System.out.println(jsonNode);
    System.out.println(jsonNode.asToken());
    System.out.println(jsonNode.getNodeType());
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();

        while (iter.hasNext()) {
          printNodeInfo(iter.next().getValue());
        }
    }
  }
}

Output:

{"binaryVal":"SXRlbU9uZQ=="}
START_OBJECT
OBJECT
"SXRlbU9uZQ=="
VALUE_EMBEDDED_OBJECT
BINARY
Exception in thread "main" java.lang.NullPointerException: unhandled token type VALUE_EMBEDDED_OBJECT
    at com.flipkart.zjsonpatch.NodeType.getNodeType(NodeType.java:87)
    at com.flipkart.zjsonpatch.JsonDiff.generateDiffs(JsonDiff.java:355)
    at com.flipkart.zjsonpatch.JsonDiff.compareObjects(JsonDiff.java:466)
    at com.flipkart.zjsonpatch.JsonDiff.generateDiffs(JsonDiff.java:363)
    at com.flipkart.zjsonpatch.JsonDiff.asJson(JsonDiff.java:60)
    at com.flipkart.zjsonpatch.JsonDiff.asJson(JsonDiff.java:46)
    at Main.main(Main.java:30)
exit status 1