Get Elements of JSON Array Android

Hey guys 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.

Answers


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.


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

o = a.getJSONObject(1);

Look here


Need Your Help

Transaction of fragments in android results in blank screen

android android-layout android-fragments

If it helps, what I want is similar to what is done in this google tutorial

Can LINQPad run SQL Queries on OData?

sql odata linqpad

I can run LINQ queries successfully to retrieve data from OData providers. I'm not able to run SQL queries with OData. Since I'm behind who knows how many firewalls at work, I'm not sure if it's LI...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.