gpt4 book ai didi

Java JsonPath 数组的长度

转载 作者:行者123 更新时间:2023-12-01 18:58:03 25 4
gpt4 key购买 nike

我有一个像这样的 Json:

{
"hello": {
"hello": [
{
"wwrjgn": "aerg",
"aaa": "gggg",
"rfshs": {
"segse": "segsegs",
"xx": "rgwgwgw",
"x-e ": "eergye"
},
"egg": "sgsese",
"segess": "sgeses",
"segess": "segess"
},
{
"esges": "segesse",
"segesg": "ws",
"rddgdr": {
"rdrdrdg": “srgsesees"
},
"drr": 3600,
"esese": "uytk",
"wew": "699",
"eses": “qe4ty"
}
],
"how": www"
}
}

我执行以下操作:

Object document = 
Configuration.defaultConfiguration().addOptions().jsonProvider()
.parse(ka.toJSONString());
int queries = JsonPath.read(document, "$..hello.length()");

System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + queries);

我得到:

nested exception is java.lang.ClassCastException: net.minidev.json.JSONArray 
cannot be cast to java.base/java.lang.Integer] with root cause
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to
java.base/java.lang.Integer

在这里尝试:http://jsonpath.herokuapp.com/?path= $..hello.length()我得到:

[
2,
2
]

这就是我需要的。

知道我做错了什么吗?提前致谢。

最佳答案

这个...

JsonPath.read(document, "$..hello.length()")

... 会将其响应转换为 net.minidev.json.JSONArray 的实例不能转换为 int 。这解释了ClassCastException

你看到的原因......

[
2,
2
]

...当尝试在线评估器时,这是toString()对于JSONArray实例返回该字符串。

要获取代码中的“查询数量的长度”,只需将 JsonPath 输出读取为 JSONArray然后获取该类型的大小属性。例如:

JSONArray read = JsonPath.read(document, "$..hello.length()");
// prints:
// THE LENGTH OF THE NUMBER OF QUERIES 2
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + read.size());

您还可以返回 List<Integer ,例如:

List<Integer> read = JsonPath.read(document, "$..hello.length()");
// prints:
// THE LENGTH OF THE NUMBER OF QUERIES 2
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + read.size());

关于Java JsonPath 数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49695958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com