Write a Java class that compares two objects and returns the difference as a string that follows json patch syntax. If the two objects compared are not primitives, it recursively compares the individual components. I already have code to compare collections.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here’s a self‐contained Java class that, given two arbitrary objects, will produce a JSON-Patch (RFC 6902) describing the differences. It uses Jackson to build the JSON and Reflection to walk your beans. You can slot in your existing collection‐diffing code in place of the diffCollection(...) stub if you wish.
java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.*;
public class JsonPatchDiff {
private static final ObjectMapper mapper = new ObjectMapper();
/**
* Generate a JSON-Patch (RFC6902) string that describes how to turn `source` into `target`.
*/
public static String generateDiff(Object source, Object target) throws JsonProcessingException {
List<ObjectNode> ops = new ArrayList<>();
diff(source, target, "", ops);
return mapper.writeValueAsString(ops);
}
private static void diff(Object src, Object tgt, String path, List<ObjectNode> ops) {
// 1) identity / both null
if (src == tgt) return;
// 2) add or remove
if (src == null && tgt != null) {
// add operation
ObjectNode op = mapper.createObjectNode();
op.put("op", "add");
op.put("path", path);
op.set("value", mapper.valueToTree(tgt));
ops.add(op);
return;
}
if (src != null && tgt == null) {
// remove operation
ObjectNode op = mapper.createObjectNode();
op.put("op", "remove");
op.put("path", path);
ops.add(op);
return;
}
// 3) primitive / String / Enum / Number / Boolean
if (isPrimitiveOrWrapper(src.getClass())) {
if (!src.equals(tgt)) {
ObjectNode op = mapper.createObjectNode();
op.put("op", "replace");
op.put("path", path);
op.set("value", mapper.valueToTree(tgt));
ops.add(op);
}
return;
}
// 4) Array
if (src.getClass().isArray() && tgt.getClass().isArray()) {
List<Object> listSrc = arrayToList(src);
List<Object> listTgt = arrayToList(tgt);
diffCollection(listSrc, listTgt, path, ops);
return;
}
// 5) Collection
if (src instanceof Collection && tgt instanceof Collection) {
diffCollection((Collection<?>) src, (Collection<?>) tgt, path, ops);
return;
}
// 6) Map
if (src instanceof Map && tgt instanceof Map) {
diffMap((Map<?, ?>) src, (Map<?, ?>) tgt, path, ops);
return;
}
// 7) Bean / POJO
diffBean(src, tgt, path, ops);
}
private static void diffBean(Object src, Object tgt, String path, List<ObjectNode> ops) {
Class<?> cls = src.getClass();
while (cls != null && cls != Object.class) {
for (Field f : cls.getDeclaredFields()) {
f.setAccessible(true);
try {
Object v1 = f.get(src);
Object v2 = f.get(tgt);
String childPath = path + "/" + f.getName();
diff(v1, v2, childPath, ops);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
cls = cls.getSuperclass();
}
}
private static void diffMap(Map<?, ?> m1, Map<?, ?> m2, String path, List<ObjectNode> ops) {
// union of keys
Set<Object> allKeys = new HashSet<>(m1.keySet());
allKeys.addAll(m2.keySet());
for (Object key : allKeys) {
String escapedKey = escapeJsonPointer(key.toString());
String childPath = path + "/" + escapedKey;
if (!m1.containsKey(key)) {
// add
ObjectNode op = mapper.createObjectNode();
op.put("op", "add");
op.put("path", childPath);
op.set("value", mapper.valueToTree(m2.get(key)));
ops.add(op);
} else if (!m2.containsKey(key)) {
// remove
ObjectNode op = mapper.createObjectNode();
op.put("op", "remove");
op.put("path", childPath);
ops.add(op);
} else {
// both exist → recurse
diff(m1.get(key), m2.get(key), childPath, ops);
}
}
}
/**
* Stub for collection diffing. Replace this with your existing implementation.
*/
private static void diffCollection(Collection<?> c1,
Collection<?> c2,
String path,
List<ObjectNode> ops) {
// Example naive implementation: compare sizes, then items by index.
// You can replace entirely with your own more sophisticated logic.
List<?> l1 = new ArrayList<>(c1);
List<?> l2 = new ArrayList<>(c2);
int max = Math.max(l1.size(), l2.size());
for (int i = 0; i < max; i++) {
String idxPath = path + "/" + i;
if (i >= l1.size()) {
// add
ObjectNode op = mapper.createObjectNode();
op.put("op", "add");
op.put("path", idxPath);
op.set("value", mapper.valueToTree(l2.get(i)));
ops.add(op);
} else if (i >= l2.size()) {
// remove
ObjectNode op = mapper.createObjectNode();
op.put("op", "remove");
op.put("path", idxPath);
ops.add(op);
} else {
diff(l1.get(i), l2.get(i), idxPath, ops);
}
}
}
// -------------------- Helpers --------------------
private static boolean isPrimitiveOrWrapper(Class<?> cls) {
return cls.isPrimitive()
|| cls == String.class
|| cls == Boolean.class
|| cls == Integer.class
|| cls == Long.class
|| cls == Short.class
|| cls == Double.class
|| cls == Float.class
|| cls == Byte.class
|| cls.isEnum();
}
private static List<Object> arrayToList(Object array) {
int len = Array.getLength(array);
List<Object> result = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
result.add(Array.get(array, i));
}
return result;
}
/**
* Per RFC6901, "/" in keys must be escaped as "~1", "~" as "~0"
*/
private static String escapeJsonPointer(String token) {
return token.replace("~", "~0").replace("/", "~1");
}
// -------------------- Example Usage --------------------
public static void main(String[] args) throws Exception {
// simple example
Map<String, Object> a = new HashMap<>();
a.put("name", "Alice");
a.put("age", 30);
a.put("tags", Arrays.asList("x", "y", "z"));
Map<String, Object> b = new HashMap<>();
b.put("name", "Bob");
b.put("tags", Arrays.asList("x", "z", "w"));
b.put("active", true);
String patch = JsonPatchDiff.generateDiff(a, b);
System.out.println(patch);
// [
// {"op":"replace","path":"/name","value":"Bob"},
// {"op":"remove","path":"/age"},
// {"op":"replace","path":"/tags/1","value":"z"},
// {"op":"replace","path":"/tags/2","value":"w"},
// {"op":"add","path":"/active","value":true}
// ]
}
}
Explanation of the main pieces:
generateDiff(…)
Sets up an empty list of JSON‐Patch ops and calls the recursive diff.
diff(…)
Handles null/add/remove.
Detects primitives & wrappers → replace if not equal.
Detects Arrays, Collections, Maps, or Beans and delegates.
diffBean(…)
Uses reflection to iterate over all fields (including inherited), recursing into each.
diffCollection(…)
A minimal index‐based algorithm—swap in your existing collection‐diff here.
diffMap(…)
Unions the key sets and emits add/remove/replace as needed.
Jackson
Builds each op as an ObjectNode, then mapper.writeValueAsString(...) to get a valid JSON array of ops.
You can customize the collection‐ and map‐diff logic (or swap in your own), tweak array handling, or add extra op types (e.g. "move", "copy"). But the above should give you a solid, recursive JSON‐Patch generator for arbitrary object‐graphs.