获取JSON数组元素Android

3

我有一个JSON文件,看起来像下面这样:

{"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},
{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}

通过以下方法,我可以获取第一组纬度和经度坐标:

JSONObject o = new JSONObject(s);
JSONArray a = o.getJSONArray("posts");
o = a.getJSONObject(0);
lat = (int) (o.getDouble("Latitude")* 1E6);
lng = (int) (o.getDouble("lontitude")* 1E6); 

有没有人知道如何获取所有的纬度和经度值?

非常感谢任何帮助。


经度。除非您不控制数据... - Karl Knechtel
3个回答

9
创建用于结果的 ArrayList:
JSONObject o = new JSONObject(s);
JSONArray a = o.getJSONArray("posts");
int arrSize = a.length();
List<Integer> lat = new ArrayList<Integer>(arrSize);
List<Integer> lon = new ArrayList<Integer>(arrSize);
for (int i = 0; i < arrSize; ++i) {
    o = a.getJSONObject(i);
    lat.add((int) (o.getDouble("Latitude")* 1E6));
    lon.add((int) (o.getDouble("lontitude")* 1E6));
}

这将涵盖任何数组大小,即使有超过两个值。

这是一个更好的答案。我只是想让你注意索引参数。 - Dani bISHOP
谢谢你的建议,Binyamin Sharet。我尝试了你提供的方法,但是没有加入数组大小。非常感谢 :) - Grady-lad
在 JSONObject 方法中,这里的 's' 是什么? - user4050065
s 是要解析的 JSON 字符串。 - MByD

2
在以下代码中,我使用Gson将JSON字符串转换为Java对象,因为GSON可以使用对象定义直接创建所需类型的对象。
String json_string  = {"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}

JsonObject out = new JsonObject();
out = new JsonParser().parse(json_string).getAsJsonObject();

JsonArray listJsonArray = new JsonArray();
listJsonArray = out.get("posts").getAsJsonArray();

Gson gson = new Gson();
Type listType = new TypeToken<Collection<Info>>() { }.getType();

private Collection<Info> infoList;
infoList = (Collection<Info>) gson.fromJson(listJsonArray, listType);
List<Info> result = new ArrayList<>(infoList);

Double lat,long;
if (result.size() > 0) {
            for (int j = 0; j < result.size(); j++) {
                lat = result.get(j).getLatitude();
                long = result.get(j).getlongitude();
            }

//Generic Class
public class Info {

    @SerializedName("Latitude")
    private Double Latitude;

    @SerializedName("longitude")
    private Double longitude;

    public Double getLatitude() {  return Latitude; }

    public Double getlongitude() {return longitude;}

    public void setMac(Double Latitude) {
         this.Latitude = Latitude;
    }

    public void setType(Double longitude) {
        this.longitude = longitude;
    }
 }

这里的结果存储在lat和long变量中。


-1

相信我的记忆和常识... 你尝试过了吗:

o = a.getJSONObject(1);

点击这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接