Parsing JSON respone

| |

if we have a JSON web service response like this:
"persons"
[
{
"person"{
"firstName": "John",
"lastName": "Smith",
"age": 25
}
}
{
"person"{
"firstName": "Catherine",
"lastName": "Jones",
"age": 35
}
}
]
this response is a JSON Array with the name "persons", this array consists of "person" JSON Objects.
to parse such a reponse:
public ArrayList<Person> getMessage(String response){
JSONObject jsonResponse;
ArrayList<Person> arrPersons=new ArrayList<Person>;
try {
// obtain the reponse
jsonResponse = new JSONObject(response);
// get the array
JSONArray persons=jsonResponse.optJSONArray("persons");
// iterate over the array and retrieve single person instances
for(int i=0;i<persons.length();i++){
// get person object
JSONObject person=persons.getJSONObject(i);
// get first name
String firstname=person.optString("firstname");
// get last name
String lastname=person.optString("lastname");
// get the age
int age=person.optInt("age");

// construct the object and add it to the arraylist
Person p=new Person();
p.firstName=firstname;
p.lastName=lastname;
p.age=age;
arrPersons.add(p);
}

} catch (JSONException e) {

e.printStackTrace();
}

return arrPersons;
}

notice that we used the methods optJSONArray,optString,optInt instead of using getString,getInt because the opt methods return empty strings or zero integers if no elements are found. while the get methods throw an exception if the element is not found.

Related Posts by Categories

0 comments:

Post a Comment