0

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);

それが役立つことを願っています。

4

4 に答える 4

0

あなたの問題はresults、、、、およびの複数の子で構成されるJSONArray子を含むです。配列には、実際にはこれらのオブジェクトの多くが含まれていますが、ここでは最初の子だけに注目しましょう。JSONObject"address_components""formatted_address""geometry""types"result

コードを注意深く見てください。この行で:

JSONArray resultArry = reader.getJSONArray("results");

全体を取得していますresults。後で、同じメソッドを再度呼び出します。

JSONArray postCodeArray  = reader.getJSONArray("address_components");

しかし、あなたは"address_components"リーダーから を求めています。そこでは、何も見つからないと思います (以前に結果全体を既に読んだことがあります)。代わりにJSONArray、既に結果全体が含まれているため、以前に取得した で作業する必要があります。 .

次のようなものを試してください:

JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");

注: JSONObject #1 (最初の 0 やその他のオブジェクトとは対照的に) を選択している理由がわかりません。また、String に postCode という名前を付けた理由もわかりません。そのため、意図を誤解していた場合は、お詫び申し上げます。

于 2014-01-20T19:08:54.753 に答える
0

解決策 各配列を取得してから、郵便番号の値を取得する必要があります。値 7 が使用されます。これは、"long_name" フィールドに郵便番号が格納されている JSONObject であるためです。

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);

それが役立つことを願っています。

于 2014-01-21T00:20:32.953 に答える