通过JSON对象迭代从服务器接收 [英] Iterating through json objects received from the server
问题描述
我有一大群从Web服务器接收的JSON对象。我想从所有的JSON对象获取的所有数据。对于我如何通过JSON对象重复的话,那所有的值可以被存储在ArrayList中。
这是从服务器接收到我的JSON对象的样本模型。我需要的所有资料(姓名和所在城市)两个的ArrayList。对于如何通过JSON对象做我的循环。没有办法获得的数据作为从服务器JSON阵列。这就是为什么我在这里问。如果是JSON数组,这本来是我更容易。所以,请帮助我..
[{姓名:阿斌,城市:AA},{姓名:亚历克斯,城市:BB},。 ......一个大集合的JSON对象...]
您可以使用的 GSON 并解析字符串到Java对象。
例如你有一个类。
公共类位置{
私人字符串名称;
私人字符串的城市;
// getter和setter
}
和你的类,你可以只解析为 Location类
GSON GSON =新GSON();
位置[]位置= gson.fromJson(jsonString,位置[]类。);
之后,你可以通过位置环
的for(int i = 0; I< locations.length;我++){
的System.out.println(位置[I] .getName());
}
如果你需要从名字单列市
ArrayList的名称=新的ArrayList();
ArrayList的城市=新的ArrayList();
的for(int i = 0; I< locations.length;我++){
name.add(位置[I] .getName());
city.add(位置[I] .getCity());
}
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 all the values can be stored on arraylist..
This is a sample model of my json object received from server. I need all the data (name and city) in two arraylists. For that how do I loop through the json objects. There is no way of getting the data as json array from the server. That's why I asked here. If it was json array, It would have been easier for me. So please help me..
[{"Name":"abin","City":"aa"},{"Name":"alex","City":"bb"},....... a large collection of json objects...]
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());
}
这篇关于通过JSON对象迭代从服务器接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!