Android 遍历从服务器接收的json对象
我从web服务器接收了大量json对象。我想从所有json对象获取所有数据。为此,我如何迭代json对象,以便所有值都可以存储在arraylist上 这是从服务器接收到的json对象的示例模型。我需要两个ArrayList中的所有数据(姓名和城市)。为此,我如何循环处理json对象。无法从服务器获取json数组形式的数据。这就是我在这里问的原因。如果是json数组,对我来说会更容易。所以请帮帮我Android 遍历从服务器接收的json对象,android,json,jsonobject,Android,Json,Jsonobject,我从web服务器接收了大量json对象。我想从所有json对象获取所有数据。为此,我如何迭代json对象,以便所有值都可以存储在arraylist上 这是从服务器接收到的json对象的示例模型。我需要两个ArrayList中的所有数据(姓名和城市)。为此,我如何循环处理json对象。无法从服务器获取json数组形式的数据。这就是我在这里问的原因。如果是json数组,对我来说会更容易。所以请帮帮我 [{"Name":"abin","City":"aa"},{"Name":"alex","City"
[{"Name":"abin","City":"aa"},{"Name":"alex","City":"bb"},....... a large collection of json objects...]
您可以使用该字符串并将其解析为java对象
例如,你有一个班级
public class Location{
private String name;
private String city;
//getters and setters
}
在您的类中,您可以将其解析为Location类
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());
}
for(int i=0;i如果您知道JSON字符串的结构,那么使用google的Gson()
(将JAR添加到您的项目中)通过3个简单的步骤进行反序列化:
创建实体类(无论对象是什么,我都以“Person”为例)
创建反序列化JSON字符串的类。在我的示例中,JSON字符串实际上是一个person数组
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
}
你确定你得到的是json吗?格式不对。是的,我确定。你为什么这么说?没有获取数组的键。我想这是json对象集合,不是一个json对象…它是一个json数组,不是json对象。它缺少获取json数组的键。如何将gson导入我的项目?你使用的是什么ide/
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
}
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
}
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