Accessing objects within nested loops using hashmap List

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-05 04:23:06

问题


I have a JSON response which I want to parse and extract the data from. Here is the JSON response

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

I want to extract each od_pair and the values of of bucket and available within them.

@Fenio's solution in Accessing jsonpath elements with nested objects has the best approaches. The code snippet that I have refactored looks like this:

List<HashMap<String, Object>> LegList = jsonPath.getList("$");

     for (HashMap<String, Object> singleLeg : LegList) {
        String OD_pair = (String) singleLeg.get("od_pair");

    //List<HashMap<String, Object>> bucketsList = jsonPath.param("j", j).getList("[j].buckets");
        List<HashMap<String, Object>> bucketsList = jsonPath.getList("singleLeg.buckets");

        for (HashMap<String, Object> singleBucket : bucketsList) {
            String BucketCode = (String) singleBucket.get("bucket");
            String Available = (String) 
singleBucket.get("available");

I want to verify if the bucketsList that I am extracting is correct. Earlier I used a for loop with the parameter j. But with this approach which is lot more cleaner and nicer, I wish to understand if I am right in the way am extracting the bucketsList


回答1:


I managed to resolve this. I understood where I was going wrong. Replacing

 List<HashMap<String, Object>> bucketsList = jsonPath.getList("singleLeg.buckets");

with this

List<HashMap<String, Object>> bucketsList = (List<HashMap<String, Object>>) singleLeg.get("buckets");

Has resolved my issue and now things work as expected.

Since I was already within singleLeg loop, all I needed to call was the buckets object within the loop rather than trying to access the buckets from the rootpath.

Big shoutout to @Fenio who advised the best approaches in Accessing jsonpath elements with nested objects



来源:https://stackoverflow.com/questions/57288085/accessing-objects-within-nested-loops-using-hashmap-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!