迭代从服务器收到的json对象

时间:2014-08-11 07:47:49

标签: android json jsonobject

我从Web服务器收到了一大组json对象。我想从所有json对象获取所有数据。为此我如何遍历json对象,以便所有值都可以存储在arraylist中。

这是从服务器收到的json对象的示例模型。我需要两个arraylists中的所有数据(名称和城市)。为此,我如何循环json对象。无法从服务器获取数据作为json数组。这就是我在这里问的原因。如果它是json数组,那对我来说会更容易。所以请帮助我..

[{"Name":"abin","City":"aa"},{"Name":"alex","City":"bb"},....... a large collection of json objects...]

2 个答案:

答案 0 :(得分:1)

您可以使用Gson并将字符串解析为java对象。

例如,你有一个班级。

public class Location{

    private String name;

    private String city;

    //getters and setters

}

在您的班级中,您只需将其解析为Location class

即可
Gson gson=new Gson();

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

之后你可以遍历位置

for(int i=0;i<locations.length;i++){

     System.out.println(locations[i].getName());

}

如果您需要将城市与名称分开

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());

}

答案 1 :(得分:0)

如果您知道JSON字符串的结构,那么使用google&#39; s Gson()(将JAR添加到您的项目中)进行反序列化,只需3个简单的步骤:

  1. 创建实体类(无论您的对象是什么,我都在给#34; Person&#34;例如)。

    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. 创建用于反序列化JSON字符串的类。在我的示例中,JSON字符串实际上是一个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. 进行实际的反序列化:

    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
    
相关问题