gpt4 book ai didi

android - 遍历从服务器接收到的 json 对象

转载 作者:行者123 更新时间:2023-11-30 02:44:49 27 4
gpt4 key购买 nike

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

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

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

最佳答案

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

例如你有一个类。

public class Location{

private String name;

private String city;

//getters and setters

}

在你的类(class)中你可以将它解析为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());

}

关于android - 遍历从服务器接收到的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25238186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com