How to get json array values ​​in android?

The JSON response value is as follows: "types" : [ "sublocality", "political" ] . How to get the first value of types or how to get the word sublocality?

+4
source share
3 answers
 String string = yourjson; JSONObject o = new JSONObject(yourjson); JSONArray a = o.getJSONArray("types"); for (int i = 0; i < a.length(); i++) { Log.d("Type", a.getString(i)); } 

That would be correct if you were only parsing the line above. Please note that to access types from the GoogleMaps geocode you should get an array of results, not component_address, then you can access the components.getJSONObject (index) object.

This is a simple implementation that only analyzes formatted_address - what I need in my project.

 private void parseJson(List<Address> address, int maxResults, byte[] data) { try { String json = new String(data, "UTF-8"); JSONObject o = new JSONObject(json); String status = o.getString("status"); if (status.equals(STATUS_OK)) { JSONArray a = o.getJSONArray("results"); for (int i = 0; i < maxResults && i < a.length(); i++) { Address current = new Address(Locale.getDefault()); JSONObject item = a.getJSONObject(i); current.setFeatureName(item.getString("formatted_address")); JSONObject location = item.getJSONObject("geometry") .getJSONObject("location"); current.setLatitude(location.getDouble("lat")); current.setLongitude(location.getDouble("lng")); address.add(current); } } catch (Throwable e) { e.printStackTrace(); } } 
+13
source

You must parse JSON to get these values. You can use the JSONObject and JSONArray classes in Android or use a library like Google GSON to get POJO from JSON.

+1
source

I would insist that you use GSON. I created a demo to parse the same answer to the card. You can find the full demo here . In addition, I created the GSON global parser class, which can be used to easily parse any response that is in JSON.

+1
source

All Articles