如何获取seat对象中json数组中的最后一个元素。我想获得值为845的countryid,但是这个json是动态的,所以我想获得seat对象中的最后一个元素。我的api是这样构造的。先感谢您。
{
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
{"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
}
答案 0 :(得分:20)
您可以通过索引访问jsonData.seats
数组,最后一项的索引等于jsonData.seats.length-1
简单地:
var countryId = jsonData.seats[jsonData.seats.length-1].countryid
答案 1 :(得分:0)
试试这个:
var jsonObject = {
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
{"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
}
var lastElement = jsonObject.seats[jsonObject.seats.length-1].countryid
答案 2 :(得分:0)
我使用了上面的建议,并将其用于GSON lib中的JsonElement对象循环中。以防万一有人在找我做的同样的事情。
for (JsonElement obj : entries){
//Do your stuff
if (entries.get(entries.size() - 1).equals(obj)){
//Do stuff if your in last position of the jsonarray array
}else{
//Do stuff until you reach the last position
}
}