我有一个像这样的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
]
这就是我需要的。
知道我做错了什么吗? 提前谢谢。
答案 0 :(得分:0)
这......
JsonPath.read(document, "$..hello.length()")
...会将其响应转换为net.minidev.json.JSONArray
的实例,该实例无法转换为int
。这解释了ClassCastException
你看到的原因......
[
2,
2
]
...在尝试在线evaulator时,这是toString()
实例返回该字符串的JSONArray
。
获得"查询数量的长度"在代码中,只需将JsonPath输出作为JSONArray
读取,然后获取该类型的size属性。例如:
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());