从以数组为根的jsonpath获取元素值

Getting element value from jsonpath whose root is an array

我有一个 JSON 响应,其中根作为 1 个或多个对象的数组。我想提取每个对象中其中一个元素的值。

这是 JSON 示例:

[  
   {  
      "od_pair":"7015400:8727100",
      "buckets":[  
         {  
            "bucket":"C00",
            "original":2,
            "available":2
         },
         {  
            "bucket":"A01",
            "original":76,
            "available":0
         },
         {  
            "bucket":"B01",
            "original":672,
            "available":480
         }
      ]
   },
   {  
      "od_pair":"7015400:8814001",
      "buckets":[  
         {  
            "bucket":"C00",
            "original":2,
            "available":2
         },
         {  
            "bucket":"A01",
            "original":40,
            "available":40
         },
         {  
            "bucket":"B01",
            "original":672,
            "available":672
         },
         {  
            "bucket":"B03",
            "original":632,
            "available":632
         },
         {  
            "bucket":"B05",
            "original":558,
            "available":558
         }
      ]
   }
]

我想访问每个对象中 od_pair 的值。

我尝试将根数组称为 $ 但这没有帮助。

这是我写的代码片段:

        List<Object> LegList = jsonPath.getList("$");
        int NoofLegs = LegList.size();
        System.out.println("No of legs :" +NoofLegs);
        for (int j=0; j<=NoofLegs;j++) {
            String OD_Pair = jsonPath.param("j", j).getString("[j].od_pair");
            System.out.println("OD Pair: " + OD_Pair);
            List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");

            int NoOfBuckets = BucketsList.size();
            System.out.println("no of Buckets: " + NoOfBuckets);
        }

这是我看到的错误:

Caused by: 
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup 
failed:
Script1.groovy: 1: unexpected token: [ @ line 1, column 27.
restAssuredJsonRootObject.[j].od_pair

有人可以帮我吗?

您从 $ 开始是对的。但是,您的特定 JSON 得到的是 HashMap<String, Object>List,其中每个 JSON 对象表示为单个 HashMap。知道可以这样获取HashMap的列表:

List<HashMap<String, Object>> jsonObjectsInArray = path.getList("$");

String 将是属性的名称。 Object 将是 StringIntegerJSONObjectJSONArray。后者不是确切的 class 名称,但它与您实现预期结果无关。

现在,我们所要做的就是遍历 HashMap 并像这样提取 od_pair 的值:

for (HashMap<String, Object> jsonObject : jsonObjectsInArray) {
    System.out.println(jsonObject.get("od_pair"));
}

输出为:

7015400:8727100
7015400:8814001

希望对您有所帮助!