I have a large group of json objects received from web server. I want to get all the data from all the json objects. For that How do I iterate through the json object so, that a
If you know the structure of your JSON String, then use google's Gson()
(add the JAR to your project) to deserialize, in 3 easy steps:
Create the Entity class (whatever your object is, I'm giving "Person" as example).
public class Person {
@Expose //this is a Gson annotation, tells Gson to serialize/deserialize the element
@SerializedName("name") //this tells Gson the name of the element as it appears in the JSON string, so it can be properly mapped in Java class
private String name;
@Expose
@SerializedName("lastName")
private String lastName;
@Expose
@SerializedName("streetName")
private String streetName;
//getters and setters follow
}
Create the class into which you deserialize the JSON string. In my example, the JSON string is actually an array of Persons.
public class PersonsList extends ArrayList implements Serializable{
//nothing else here
}
If the JSON string has a named key, then you don't have to extend ArrayList:
public class PersonsList implements Serializable{
@Expose
@SerializedName("persons")
private ArrayList persons;
//getters / setters
}
Do the actual deserialization:
String json = "[{person1},{person2},{person3}]";//your json here
Gson gson = new Gson();
PersonsList personsList = gson.fromJson(json, PersonsList.class);
//then, depending on how you build PersonsList class, you iterate:
for(Person p : personsList)//if you extended ArrayList
//or
for(Person p : personsList.getPersons())//if it's the second option