JSON ページの例 http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
@SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
このコードは、アドレスを正しく返します。address_components 内にある郵便番号 long_name を取得するにはどうすればよいですか?
解決策 各配列を取得してから、郵便番号の値を取得する必要がありました。「long_name」フィールドに郵便番号が格納されている JSONObject であるため、値 7 を使用しています。
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
それが役立つことを願っています。