问题
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