zjsonpatch是用Java编写的RFC 6902 JSON Patch的实现。github地址:https://github.com/flipkart-incubator/zjsonpatch
1、描述:
2、功能:
根据上篇blog(https://blog.csdn.net/liuxiao723846/article/details/108508200)可知,RFC 6902 JSON Patch标准定义了以下五种operations:add、remove、replace、move、copy
maven pom.xml:
com.flipkart.zjsonpatch
zjsonpatch
{version}
这里使用了最新版本0.4.11,可以通过https://search.maven.org/search?q=g:com.flipkart.zjsonpatch 查找对应的版本,也可以在github 上的release上找对应的版本https://github.com/flipkart-incubator/zjsonpatch/releases
1、获取json diff信息作为patch:
public class PatchTest {
private static final ObjectMapper mapper = new ObjectMapper();
private static String json1 = "{\"a\":0,\"b\":[1,2]}";
private static String json2 = "{\"b\": [1,2,0]} ";
public static void main(String... str) {
//JsonNode patch = JsonDiff.asJson(JsonNode source, JsonNode target)
JsonNode patch = JsonDiff.asJson(mapper.readTree(json1),mapper.readTree(json2));
System.out.println(patch.toPrettyString());
}
输出:[{"op":"move","from":"/a","path":"/b/2"}]
2、关闭move、copy operations:
上面的输出可以看到,默认情况下计算两个json文档的diff(patch)信息时会使用move、copy这样的operations,虽然这两个operations很有用,但实际业务中有时不需要这样,只想表达成最简单的add、remove、replace这种operations。
private static EnumSet flags = DiffFlags.dontNormalizeOpIntoMoveAndCopy().clone();
JsonNode patch = JsonDiff.asJson(mapper.readTree(json1),mapper.readTree(json2),flags );
输出:[{"op":"remove","path":"/a","value":0},{"op":"add","path":"/b/2","value":0}]
3、应用patch:
通过diff计算出来的patch,可以应用到一个json文档上,并返回patch后的json文档。这个过程是对原json文档的一个克隆,所以不会修改原sjon文档的内容。
public class PatchTest {
private static final ObjectMapper mapper = new ObjectMapper();
private static EnumSet flags = DiffFlags.dontNormalizeOpIntoMoveAndCopy().clone();
private static String json1 = "{\"a\":0,\"b\":[1,2]}";
private static String json2 = "{\"b\": [1,2,0]} ";
public static void main(String... str) {
//JsonNode patch = JsonDiff.asJson(JsonNode source, JsonNode target)
JsonNode patch = JsonDiff.asJson(mapper.readTree(json1),mapper.readTree(json2));
//System.out.println(patch.toPrettyString());
//JsonNode target = JsonPatch.apply(JsonNode patch, JsonNode source);
JsonNode target = JsonPatch.apply(patch, mapper.readTree(json1));
System.out.println(target .toPrettyString());
}
输出:{"b":[1,2,0]}