简体   繁体   中英

Java JsonPath length of array

I have a Json like this:

{
    "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"
    }
}

I do the following:

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);

I get:

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

Trying it here: http://jsonpath.herokuapp.com/?path= $..hello.length() I get:

[
   2,
   2
]

Which is what i need.

Any idea what i am doing wrong? Thanks in advance.

This ...

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

... will cast its response an instance of net.minidev.json.JSONArray which cannot be cast to an int . This explains the ClassCastException

The reason you see ...

[
   2,
   2
]

... when trying the online evaulator is that this is the toString() for the JSONArray instance returns that String.

To get the "THE LENGTH OF THE NUMBER OF QUERIES " in code, just read the JsonPath output as a JSONArray and then get the size attribute of that type. For example:

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());

You could also return a List<Integer , for example:

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM