使用JsonPath表达式获取数组大小 - Stefan Goessner的JsonPath

39

我在使用 Stefan Goessner 的 JsonPath 时遇到了一个问题,无法找到数组或列表的大小。我正在使用版本为 json-path-2.0.0。

我的 JsonPath 表达式是 $.orders.length,JSON 数据看起来像这样:

{
  "orders" : [
    ...
  ]
}

以下错误导致其失败:

com.jayway.jsonpath.PathNotFoundException: Property ['length'] not found in path $['orders']

我也尝试使用 $.orders.length(),但仍然会出现以下错误:

com.jayway.jsonpath.PathNotFoundException: 在路径 $['orders'] 中未找到属性 ['length()']

请建议我如何使用Goessner的JsonPath表达式获取数组的长度。

[编辑] 以下是我获取配置的方式:

    com.jayway.jsonpath.Configuration conf = com.jayway.jsonpath.Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
    DocumentContext documentContext = JsonPath.using(conf).parse(orderJson);
    Object val = documentContext.read(jsonPathExpression);
5个回答

89

似乎jayway json-path库版本2.1.0才开始支持返回数组长度的length()方法,具体详情可参考这里

根据快速测试来看,在版本2.1.0和版本2.2.0中,$.orders.length()表达式都能正常工作,因此你只需要升级依赖版本即可修复你所见到的错误。


一个小修正,似乎应该是$.orders.length(没有括号),我刚测试了一下,对我来说可以正常工作。 - Alex Rewa
@AlexRewa 我尝试了一下,但是出现了错误信息java.lang.AssertionError: No value at JSON path "$.length"。但是"$.length()"可以正常工作。 - Võ Quang Hòa
@VõQuangHòa,奇怪...似乎这取决于JsonPath的实现。 - Alex Rewa
$.length() 在 json-path 2.7 上起作用。 - undefined

3
在Spring WebFlux中使用WebClient。
....
 .jsonPath("$.length()").isEqualTo(2);
...

我以以下方式使用了你的解决方案,它像魔法一样奏效了! 这是为了特别检查一个数组是否为空并且没有对象但不为 null。 resultActions.andExpect(jsonPath('$.benefitsSummaryResponse.financialData.limitList.length()', is(0)) ) - Aniket

0

计算 JSON 数组中元素数量的方法 这是我的解决方案

myJson -> 包含数组的 JSON

fieldPath -> 数组的路径

import com.jayway.jsonpath.JsonPath;
import org.json.JSONArray;
import org.json.simple.JSONObject;

JSONObject myJson;

    public long CountFields(String fieldPath) {
      String onlyMyArray=JsonPath.parse(myJson).read(fieldPath).toString();
      JSONArray jsonArray = new JSONArray(onlyMyArray);
      return jsonArray.length();
                       }

-2
            JsonPath js = new JsonPath(response);
           List values = js.getList("Mention the path of the json here");
           int size= values.size();
           System.out.println(size);

-5
List values = jsonpath.getList("orders");
System.out.println("Size of object : "+ values.size());

5
请始终在代码中添加解释。这将提高答案的质量。 - DaFois
这是我在StackOverflow上见过的最被踩的有用且正确的答案。JsonPath的getList()方法对我非常有帮助,实际上这就是我用来解决问题的答案。我正在整理这个答案,希望它能从-6爬回来哈哈。 - emery

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接