Android - How to parse JSONObject and JSONArrays

My build is Android 2.2 Google API 8, Im running on an emulator. I am trying to try to access a location in this JSON object. I get it after using

InputStream instream = entity.getContent(); JSONObject myAwway = new JSONObject(convertStreamToString(instream)); 

Google docs say it returns an array, but with surrounding curly braces. It looks like an object.

I need to access lat and lon in the location field and save as doubling.

Ive searched, but only seemed to find help with simple files.

 { "results" : [ { "address_components" : [ { "long_name" : "20059", "short_name" : "20059", "types" : [ "postal_code" ] }, { "long_name" : "Washington DC", "short_name" : "Washington DC", "types" : [ "locality", "political" ] }, { "long_name" : "District of Columbia", "short_name" : "DC", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] } ], "formatted_address" : "Washington DC, DC 20059, USA", "geometry" : { "bounds" : { "northeast" : { "lat" : 38.924920, "lng" : -77.0178720 }, "southwest" : { "lat" : 38.9189910, "lng" : -77.02261200000001 } }, "location" : { "lat" : 38.92177780, "lng" : -77.01974260 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 38.92510312068017, "lng" : -77.01709437931984 }, "southwest" : { "lat" : 38.91880787931983, "lng" : -77.02338962068018 } } }, "types" : [ "postal_code" ] } ], "status" : "OK" } 
0
source share
2 answers
 JSONObject location = myAwway.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location"); double lat = location.getDouble("lat"); double lng = location.getDouble("lng"); 

"Results" JSONArray is probably an array of Google documents. They just wrapped it in a JSONObject with status so you can check the status before trying to work with the returned value.

+2
source
 JSONObject jObject = new JSONObject(convertStreamToString(instream)); JSONArray results = jObject.getJSONArray("result"); JSONObject geometry = results.getJSONObject(2); JSONObject bounds = geometry.getJSONObject("bounds"); JSONObject northeast = geometry.getJSONObject("northeast"); double nLat = Double.parseDouble(northeast.getString("lat").toString()); double nLng = Double.parseDouble(northeast.getString("lng").toString()); 

This should give you lat / lng for the northeast as a doubling. The southeast is the same as in the northeast, for the southeast.

+4
source

Source: https://habr.com/ru/post/945830/


All Articles