Iterating through json objects received from the server

前端 未结 2 699
生来不讨喜
生来不讨喜 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<Person> 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<Person> 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
      
    0 讨论(0)
  • 2021-01-25 05:57

    You could use Gson and parse the string to a java object.

    For example you have a class.

    public class Location{
    
        private String name;
    
        private String city;
    
        //getters and setters
    
    }
    

    and in your class you could just parse it to Location class

    Gson gson=new Gson();
    
    Location[] locations=gson.fromJson(jsonString,Location[].class);
    

    after that you could loop through the locations

    for(int i=0;i<locations.length;i++){
    
         System.out.println(locations[i].getName());
    
    }
    

    if you need to separate the city from the name

    ArrayList name=new ArrayList();
    ArrayList city=new ArrayList();
    
    for(int i=0;i<locations.length;i++){
    
       name.add(locations[i].getName());
        city.add(locations[i].getCity());
    
    }
    
    0 讨论(0)
提交回复
热议问题