嘿伙计们我有一个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);
有没有人知道如何获得所有纬度和纬度值?
非常感谢任何帮助。
答案 0 :(得分: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));
}
这将覆盖任何数组大小,即使有两个以上的值。
答案 1 :(得分:2)
在下面的代码中,我使用Gson将JSON字符串转换为java对象,因为GSON可以使用Object定义直接创建所需类型的对象。
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变量中获得的。
答案 2 :(得分:-1)