extracting single element from jsonpath array afte

2019-08-15 05:35发布

问题:

I am trying to extract a value from a json string using json-path. I suspected that my question is related to Get specific object from JSONPath array result after predicate is applied but the link didn't provide me with the answer. My jsonfile looks like this:

{
  "success": true,
  "errorKey": null,
  "results": {
    "payments": [
      {
        "name": "current",
        "all": {
          "revenue": 390.32,
          "count": 1
        }
      },
      {
        "name": "sameYesterday",
        "all": {
          "revenue": 613.24,
          "count": 4
        }
      },
      {
        "name": "yesterday",
        "all": {
          "revenue": 613.24,
          "count": 3
        }
      }
    ]
  }
}

I want to get yesterday's payment count. Following query definitely works, but it relies on the position of elements within the json array, which can change:

ReadContext ctx = JsonPath.parse(content);
ctx.read("$.results.payments[2].all.count");

I was trying to work with name matching:

ctx.read("$.results.payments[?(@.name=='yesterday')].all.count[0]")

My problem is that this always returns an empty array. ctx.read("$.results.payments[?(@.name=='yesterday')].all.count" returns [3] (logically) and I assumed taking the first element from the result array would be sufficient, but my result array is always empty. What am I doing wrong?

回答1:

count property itself is not an array in your JSON so array notation on count such as count[0] doesn't work. But the expression $.results.payments[?(@.name == 'yesterday')].all.count when evaluated returns a Java list so to get the first count we can just get the first element from the list:

List<Integer> yesterdayCounts = ctx.read("$.results.payments[?(@.name == 'yesterday')].all.count");
int firstCount = yesterdayCounts.get(0);

assertThat(firstCount).isEqualTo(3);


标签: java jsonpath