代码之家  ›  专栏  ›  技术社区  ›  user6671584

Java JsonPath数组长度

  •  3
  • user6671584  · 技术社区  · 6 年前

    我有这样一个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= $。。你好长度() 我得到:

    [
       2,
       2
    ]
    

    这正是我需要的。

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

    1 回复  |  直到 6 年前
        1
  •  0
  •   glytching    6 年前

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

    。。。将其响应转换为 net.minidev.json.JSONArray 无法转换为 int 。这解释了 ClassCastException

    你看到的原因。。。

    [
       2,
       2
    ]
    

    。。。在尝试在线评估时,这是 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());