There is such a JSON:

{ "results" : [ { "address_components" : [ { "long_name" : "277", "short_name" : "277", "types" : [ "street_number" ] }, { "long_name" : "Bedford Avenue", "short_name" : "Bedford Ave", "types" : [ "route" ] }, { "long_name" : "Williamsburg", "short_name" : "Williamsburg", "types" : [ "neighborhood", "political" ] }, { "long_name" : "Brooklyn", "short_name" : "Brooklyn", "types" : [ "sublocality", "political" ] }, { "long_name" : "Kings", "short_name" : "Kings", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "New York", "short_name" : "NY", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "11211", "short_name" : "11211", "types" : [ "postal_code" ] } ], "formatted_address" : "277 Bedford Avenue, Brooklyn, NY 11211, USA", "geometry" : { "location" : { "lat" : 40.714232, "lng" : -73.9612889 }, "location_type" : "ROOFTOP", "viewport" : { "northeast" : { "lat" : 40.7155809802915, "lng" : -73.9599399197085 }, "southwest" : { "lat" : 40.7128830197085, "lng" : -73.96263788029151 } } }, "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA", "types" : [ "street_address" ] }, // ... Additional results truncated in this example[] ... ], "status" : "OK" } 

You should read formatted_address from it. But the problem is that there are several of them. In the example, did not insert. Here's how to get it and read it? I try this:

  JSONArray fa = (JSONArray) resultJson.get("results"); Iterator i = fa.iterator(); while (i.hasNext()) { JSONObject adr = (JSONObject) i.next(); String title = (String) adr.get("formatted_address"); System.out.println(title); } 

As a result, all formatted_address are read. And I need only the first. How to implement it? Thank.

  • the first in the first element of the results array? So take away while - Komdosh
  • Thank. The same is necessary. and did not think. And how can you get to the rest? For example, to "address_components" and read "long_name"? - Kamenev_D

1 answer 1

Refer simply to the index, why are you iterating over the entire array?

 // Получаем весь массив JSONArray results = resultJson.getJSONArray("results"); // По индексу 0 получаем первый элемент JSONObject firstResult = results.getJSONObject(0); // Достаём нужное поле String formattedAddress = firstResult.getString("formatted_address"); 

If the results array can be empty, just add a size check before getting the item by index.

Get other data:

 // Получаем массив 'address_components' // из первого элемента из массива 'results' JSONArray addressComponents = firstResult.getJSONArray("address_components"); // Получаем по индексу первый элемент этого массива JSONObject firstAddressComponent = addressComponents.getJSONObject(0); // Получаем нужное поле String longName = firstAddressComponent.getString("long_name");