Parsing JSON respone:
"persons"this response is a JSON Array with the name "persons", this array consists of "person" JSON Objects.
[
{
"person"{
"firstName": "John",
"lastName": "Smith",
"age": 25
}
}
{
"person"{
"firstName": "Catherine",
"lastName": "Jones",
"age": 35
}
}
]
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.
No comments: