JSON Patch java库之json-patch

介绍

json-patch是Java编写的RFC 6902(JSON Patch)和RFC 7386(JSON Merge Patch)的实现,其核心使用Jackson(2.2.x)。github地址:https://github.com/java-json-tools/json-patch

功能描述:

  • 支持全部的RFC 6902 operations,包括test;
  • 带有operations分解的JSON diff(仅RFC 6902)。
     

示例

maven pom.xml:


    com.github.java-json-tools
    json-patch
    yourVersionHere

当前版本是1.13,也可以在github 上的release上找对应的版本:https://github.com/java-json-tools/json-patch/releases

1、获取json diff信息作为patch:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.JsonPatch;
import com.github.fge.jsonpatch.diff.JsonDiff;

public class PatchTest3 {
	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[] args) throws IOException {
		
		//JsonPatch patch = JsonDiff.asJsonPatch(source, target);
		JsonPatch patch = JsonDiff.asJsonPatch(mapper.readTree(json1), mapper.readTree(json2));
		System.out.println(patch.toString()); 
	}
}

输出:[op: move; from: "/a"; path: "/b/-"]

2、应用patch:

public class PatchTest3 {
	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[] args) throws Exception {
		
		//JsonPatch patch = JsonDiff.asJsonPatch(source, target);
		JsonPatch patch = JsonDiff.asJsonPatch(mapper.readTree(json1), mapper.readTree(json2));
		//System.out.println(patch.toString()); 
		
		
		JsonNode apply = patch.apply(mapper.readTree(json1));
		System.out.println(apply.toPrettyString());
	}
}

输出:{"b":[1,2,0]}

3、json-patch和zjsonpatch库对比:

上篇blog(https://blog.csdn.net/liuxiao723846/article/details/108547659)介绍了zjsonpatch库,对比二者的区别:

  • 前者支持关闭move、copy operations,json-patch这个库不支持关闭;(见github的issue:https://github.com/java-json-tools/json-patch/issues)
  • json-patch返回的diff信息直接就是jsonPatch对象,而不是JSONNode

JSON Patch java库之json-patch_第1张图片

综上来看,还是推荐使用zjsonpatch 

你可能感兴趣的:(java)