3

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.

peterh
  • 11,875
  • 18
  • 85
  • 108
Grady-lad
  • 105
  • 1
  • 2
  • 9

3 Answers3

9

Create ArrayLists 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.

MByD
  • 135,866
  • 28
  • 264
  • 277
2

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.

Rohit Gurjar
  • 437
  • 4
  • 12
-1

Trusting my memory and my common sense... have you tried:

o = a.getJSONObject(1);

Look here

Community
  • 1
  • 1
Dani bISHOP
  • 1,226
  • 11
  • 18