Reputation: 105
I have a JSON file which looks like the following:
{"posts":[{"Latitude":"53.38246685","lontitude":"-6.41501535"},
{"Latitude":"53.4062787","lontitude":"-6.3767205"}]}
and I can get the first set of latitude and lontitude co-ordinates by doing the following:
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);
Does anyone have an idea of how to get all the latitude and lontitude values ?
Any help would be much appreciated.
Upvotes: 3
Views: 22571
Reputation: 447
In the below code, I am using Gson for converting JSON string into java object because GSON can use the Object definition to directly create an object of the desired type.
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;
}
}
Here the result is obtained in lat and long variable.
Upvotes: 2
Reputation: 1289
Trusting my memory and my common sense... have you tried:
o = a.getJSONObject(1);
Look here
Upvotes: -1
Reputation: 137272
Create ArrayList
s for the results:
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));
}
This will cover any array size, even if there are more than two values.
Upvotes: 9