如何解析以下JSON数组?

时间:2015-09-17 12:00:38

标签: java json

我很难弄清楚如何解析以下JSON(动态):

[{
"existingData": [
  0,
  0
],
"guestId": {
  "__type": "Pointer",
  "objectId": "EB1rr6Lqtp"
},
"listingAddressGeopoint": {
  "__type": "GeoPoint",
  "latitude": 36.002702,
  "longitude": -78.90682099999998
},
"numberOfListingImages": 1,
"preferredGender": "\"Female\"",
"urlOfListingBeds": [
  "https://xyz.image0.jpg"
],
"urlOfPrimaryImage": null,
"createdAt": "2015-09-09T14:54:36.139Z",
"updatedAt": "2015-09-15T14:46:41.988Z",
"user": {
  "createdAt": "2015-09-09T14:54:34.841Z",
  "updatedAt": "2015-09-09T14:54:34.841Z"
   }
}]

问题是有时数据开始previuosData而不是来自existingData。如何在Some对象列表中获取urlOfListingBeds数组?

模型类

public class Image {
    public List<String> urlOfListingBeds;
}

修改-1

我尝试通过以下代码访问它,但它正在抛出错误

 for (int i = 0; i < rjson.size(); i++) {
        rjson.getAsJsonObject(i);
    }

其中rjson为JsonArray

1 个答案:

答案 0 :(得分:1)

通过调用getAsJsonArray()从json对象获取JsonArray。通过调用JsonArray#iterator创建一个迭代器,并遍历每个JsonElement,并通过调用JsonObject获取JsonElement#getAsJsonObject()

获得JsonObject后,您会找到urlOfListingBeds

代码:

JsonArray array= rjson.getAsJsonArray();
Iterator iterator = array.iterator();
List<String> urlOfListingBeds = new ArrayList<String>();
while(iterator.hasNext()){
    JsonElement jsonElement = (JsonElement)iterator.next();
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonArray urlOfListingBed = jsonObject.getAsJsonArray("urlOfListingBeds");
    if(urlOfListingBed!=null){
        Iterator iter = urlOfListingBed.iterator();
        while(iter.hasNext()){
            JsonElement jsonElementChild = (JsonElement)iter.next();
            if(jsonElementChild!=null)
                urlOfListingBeds.add(jsonElement.getAsString());
        }
    }
}