I made a simple JSON parser using this. All I want to do is parse the name and lat/lng of businesses with the Google maps api, but I cant seem to get it to parse correctly.
Example of JSON results:
"results" : [
{
"geometry" : {
"location" : {
"lat" : 41.8881090,
"lng" : -87.6308430
}
},
"name" : "American Bar Association",
},
{
"geometry" : {
"location" : {
"lat" : 41.8721230,
"lng" : -87.6294680
}
},
"name" : "Bar Louie",
} ], "status" : "OK"}
I took out some of the other details Im not interested in to shorten the example, but here’s my code:
JSONParser jParse = new JSONParser();
JSONObject json = jParse.getJSON(url);
try
{
JSONArray contacts = json.getJSONArray("results"); //Parent Node
for(int i = 0; i < 5; i++)//Loop through first 5 results results
{
JSONObject c = contacts.getJSONObject(i);
name = c.getString("name");//Gets name field
//get lat from location which is a sub object of geometry
lat = Float.valueOf (contacts.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getString("lat"));
}
} catch (JSONException e) { e.printStackTrace(); }
When I run it I get the first result just fine, I get the correct Name and Latitude but instead of moving to the second result it moves to the last result of i and prints its for the rest of the loop. Hard to explain, what I mean is if I loop through 5 results I get:
- Loop 1 Output: Result#1 //This is good
- Loop 2 Output: Results#5 //Somehow we skip to result #5 instead of getting #2
- Loop 3 Output: Results#5 //Now it just keeps printing #5 each time through the rest of the loop
- Loop 4 Output: Results#5
- Loop 5 Output: Results#5
I have no idea how its just ignoring the for loop and getting to the last result? Im printing the result with just a Toast message which I left out for a shorter snippet.
(I will note I am running this through a separate thread and using a handler to display the Toast message, if that matters)
I’m really not that great in Java and the it’s the first time I’ve worked with JSON so spare any stupidity I may have said. Any help is much appreciated. 🙂
I ended up answering my own problem. I think it was because I re-used the name variable each time through the loop and by the time the handler kicked in and finished displayed the first message the loop had already finished and assigned name the last value. So when the other 4 handler requests finally got executed it just printed the same value 4 times.