复杂的Json Parsing在Android中

时间:2012-04-19 09:47:19

标签: android json parsing

在我的应用程序中,我想解析格式为

的json响应
{"quote":[{"orderId":"3209926"},{"totalpages":1}]} 

下面是我所做的代码,但问题是如何获得“totalpages”值?

  try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
                 {
        JSONObject offerObject = jArray.getJSONObject(i);
        current.orderId = offerObject.getInt("orderId");

使用时显示错误

 current.totalpage= offerObject.getInt("totalpages");

有人知道如何解析这个吗?提前谢谢

2 个答案:

答案 0 :(得分:3)

如果对象不包含请求的密钥,请注意getInt()JSONObject的其他get函数一样抛出JSONException。因此,在您请求密钥之前,您应该使用hasKey()来确定对象是否包含密钥。

例如,在for循环中,您可以执行以下操作:

JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
    current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
    current.totalpage= offerObject.getInt("totalpages");
}

您还可以在循环后添加标记和检查,以确保在JSON数据中同时存在orderId和totalpages。

答案 1 :(得分:1)

我不知道为什么你的json有这种结构。但是如果你想解析它,那么你必须使用has函数执行以下操作。

for (int i = 0; i < jArray.length(); i++) {
        JSONObject offerObject = jArray.getJSONObject(i);
        if(offerObject.has("orderId")) {
          current.orderId = offerObject.getInt("orderId");
        } else if(offerObject.has("totalpages")) {
          current.totalpage= offerObject.getInt("totalpages");
        }
}