KP_
KP_

Reputation: 1866

complex Json Parsing in Android

In my app, i want to parse json response which is in the format

{"quote":[{"orderId":"3209926"},{"totalpages":1}]} 

below is the code which i had done,But the problem is how to get the "totalpages" value?

  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");

It shows error when i use

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

Anybody knows how to parse this?THanks in advance

Upvotes: 0

Views: 381

Answers (2)

Josnidhin
Josnidhin

Reputation: 12504

I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.

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");
        }
}

Upvotes: 1

Adam Zalcman
Adam Zalcman

Reputation: 27233

Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.

For example, inside the for loop you can do the following:

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

You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.

Upvotes: 3

Related Questions