Iterating through json objects received from the server

前端 未结 2 706
生来不讨喜
生来不讨喜 2021-01-25 05:20

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

2条回答
  •  有刺的猬
    2021-01-25 05:40

    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:

    1. 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
      }
      
    2. 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
      }
      
    3. 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
      

提交回复
热议问题