简体   繁体   中英

Array size using jsonpath expression - Stefan Goessner JsonPath

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.

My jsonpath expression is $.orders.length and JSON looks something like this:

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

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.

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

It seems that support for returning the length() of an array was only added in version 2.1.0 of the jayway json-path library.

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.

List values = jsonpath.getList("orders");
System.out.println("Size of object : "+ values.size());
            JsonPath js = new JsonPath(response);
           List values = js.getList("Mention the path of the json here");
           int size= values.size();
           System.out.println(size);

The way to count number of elements in json array this is how i solve it

myJson ->My Json that inside it exist an array

fieldPath -> the path to the array

import com.jayway.jsonpath.JsonPath;
import org.json.JSONArray;
import org.json.simple.JSONObject;

JSONObject myJson;

    public long CountFields(String fieldPath) {
      String onlyMyArray=JsonPath.parse(myJson).read(fieldPath).toString();
      JSONArray jsonArray = new JSONArray(onlyMyArray);
      return jsonArray.length();
                       }

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