Java:fastjosn - 根据 JSONPath 删除元素的坑

继续 json 系列:

上次说到fastjson JSON.isValid 判断是否 Json 字符串非预期,那用什么可以呢?

经验证,可以用 com.alibaba.fastjson.PATH.isValidObject("str")PATH.isValidObject("str")来判断,即使是 “0” 也不会像 PATH.isValid(“0”) 返回非预期的 true

这次再说下另外一个坑(当前最新版本1.2.75):


JSONPath.remove 的坑

比对 json 时,忽略某些字段,比较简单的方式是直接用 JSONPath 把这些字段从比对目标中剔除。这也是剔除过程中踩到的坑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"type" : "iPhone",
"number": "0123-4567-8888"
},
{
"type" : "home",
"number": "0123-4567-8910"
}
]
}
  • 目标: 删除 phoneNumbers 数组中的对象的 type。
  • 方法:com.alibaba.fastjson.JSONPath.remove(Object root, String path)

  • 参数 JSONPath:下述 JSONPath 虽然在 http://jsonpath.com/ 验证通过,但是 JSONPath.remove 却删除失败了。

    • "$.phoneNumbers[:].type"
    • "$.phoneNumbers[*].type"

需要写成 "$.phoneNumbers[0:].type" 才可以。
附完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
String jsonStr = "{\n" +
" \"firstName\": \"John\",\n" +
" \"lastName\" : \"doe\",\n" +
" \"age\" : 26,\n" +
" \"address\" : {\n" +
" \"streetAddress\": \"naist street\",\n" +
" \"city\" : \"Nara\",\n" +
" \"postalCode\" : \"630-0192\"\n" +
" },\n" +
" \"phoneNumbers\": [\n" +
" {\n" +
" \"type\" : \"iPhone\",\n" +
" \"number\": \"0123-4567-8888\"\n" +
" },\n" +
" {\n" +
" \"type\" : \"home\",\n" +
" \"number\": \"0123-4567-8910\"\n" +
" }\n" +
" ]\n" +
"}";

JSONObject jo = JSONObject.parseObject(jsonStr);
System.out.println("---------- before ----------\n"
+ JSON.toJSONString(jo, SerializerFeature.PrettyFormat));
JSONPath.remove(jo, "$.phoneNumbers[0:].type");
System.out.println("---------- after ----------\n"
+ JSON.toJSONString(jo, SerializerFeature.PrettyFormat));

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
---------- before ----------
{
"firstName":"John",
"lastName":"doe",
"address":{
"streetAddress":"naist street",
"city":"Nara",
"postalCode":"630-0192"
},
"age":26,
"phoneNumbers":[
{
"number":"0123-4567-8888",
"type":"iPhone"
},
{
"number":"0123-4567-8910",
"type":"home"
}
]
}
---------- after ----------
{
"firstName":"John",
"lastName":"doe",
"address":{
"streetAddress":"naist street",
"city":"Nara",
"postalCode":"630-0192"
},
"age":26,
"phoneNumbers":[
{
"number":"0123-4567-8888"
},
{
"number":"0123-4567-8910"
}
]
}

可以看到 phoneNumbers 数组中对象的 type 字段已被删除。

注:JSON.toJSONString(jo, SerializerFeature.PrettyFormat) 实现格式化美化输出。