JSON Patch的一大优势在于它的请求操作体很小,只发送对象的更改内容。相对要谨慎一点,只更新请求的内容。
{ "op": "copy", "from": "/biscuits/0", "path": "/best_biscuit" }
{ "op": "test", "path": "/best_biscuit/name", "value": "Choco Leibniz" }
原始文件
{
"baz": "qux",
"foo": "bar"
}
补丁
[
{ "op": "replace", "path": "/baz", "value": "boo" },
{ "op": "add", "path": "/hello", "value": ["world"] },
{ "op": "remove", "path": "/foo" }
]
结果
{
"baz": "boo",
"hello": ["world"]
}
package com.alibaba.fastjson;
public class JSONPatch {
public static String apply(String original, String patch);
public static Object apply(Object object, String patch);
}
JSONPatch执行了三个操作:
String original = "{\n" +
" \"baz\": \"qux\",\n" +
" \"foo\": \"bar\"\n" +
"}";
String patch = "[\n" +
" { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n" +
" { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n" +
" { \"op\": \"remove\", \"path\": \"/foo\" }\n" +
"]";
String result = JSONPatch.apply(original, patch);
assertEquals("{\"baz\":\"boo\",\"hello\":[\"world\"]}", result);
参考资料:
FastJSON的JSONPatch介绍:https://github.com/alibaba/fastjson/wiki/jsonpatch