Java 使用 jsonpath 表达式的数组大小 - Stefan Goessner JsonPath
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36964936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array size using jsonpath expression - Stefan Goessner JsonPath
提问by Nagendra Varma
I'm having a problem with finding an array or list size using Stefan Goessner's JsonPath. I'm using the version json-path-2.0.0.
我在使用 Stefan Goessner 的 JsonPath 查找数组或列表大小时遇到问题。我正在使用 json-path-2.0.0 版本。
My jsonpath expression is $.orders.length
and JSON looks something like this:
我的 jsonpath 表达式$.orders.length
和 JSON 看起来像这样:
{
"orders" : [
...
]
}
Its failing with the following error:
它失败并出现以下错误:
com.jayway.jsonpath.PathNotFoundException: Property ['length'] not found in path $['orders']
And I tried with $.orders.length()
too which is again failing with the below error:
我也尝试$.orders.length()
过,但再次失败并出现以下错误:
com.jayway.jsonpath.PathNotFoundException: Property ['length()'] not found in path $['orders']
com.jayway.jsonpath.PathNotFoundException: Property ['length()'] not found in path $['orders']
Please suggest me how to get the length of the array using Goessner's JsonPath expression.
请建议我如何使用 Goessner 的 JsonPath 表达式获取数组的长度。
[EDIT]Following is how I'm obtaining the configuration:
[编辑]以下是我获取配置的方式:
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);
采纳答案by andersschuller
It seems that support for returning the length()
of an array was only added in version 2.1.0of the jayway json-path library.
似乎length()
只在jayway json-path 库的2.1.0 版中添加了对返回数组的支持。
Based on some quick tests, the $.orders.length()
expression seems to work with both version 2.1.0 and version 2.2.0, so I think you just need to upgrade your dependency version in order to fix the error you are seeing.
根据一些快速测试,该$.orders.length()
表达式似乎适用于 2.1.0 版和 2.2.0 版,所以我认为您只需要升级您的依赖版本即可修复您看到的错误。
回答by Shibu
List values = jsonpath.getList("orders");
System.out.println("Size of object : "+ values.size());