1

次のjsonから地域名を取得しようとしています

http://maps.googleapis.com/maps/api/geocode/json?latlng=18.486096,73.802027&sensor=falseJSONを返す特定のアドレス。APIを使用してジオコードを逆ジオコーディングするAndroidアプリを開発しています。

これは以下のコードです..

public class MyGeocoder 
{
public static String getUserLocation(Location loc) {

    String userlocation = null;
    String readUserFeed = readUserLocationFeed((Double.toString(loc.getLatitude())) +
    ","+( Double.toString(loc.getLongitude())));
    try {
        //JSONObject Strjson = new JSONObject(readUserFeed);
        JSONArray jsonArray = new JSONArray(readUserFeed);
        JSONObject jsonObject=jsonArray.getJSONObject(0);
        userlocation = jsonObject.getString("locality").toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("User Location ", userlocation);
    return userlocation;
}

  public static String readUserLocationFeed(String address) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?
    latlng="+ address + "&sensor=false");
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            //Log.e(ReverseGeocode.class.toString(), "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}
}    
4

1 に答える 1

0

jsonの解析については、間違っています。まず、url は「結果」とフィールド「ステータスJSONObject」を含む を返します。したがって、次の行のコメントを解除する必要があります。JSONArray

JSONObject Strjson = new JSONObject(readUserFeed);

そして、statusフィールドの値をチェックして、問題がなく、次のようなデータがあることを確認することをお勧めします。

if(Strjson.getString("status").equals("OK")) { ... }

次に、次を使用して取得JSONArrayします。

JSONArray result = Strjson.getJSONArray("result");

それぞれを繰り返してJSONObject必要なフィールド値を取得しますが、取得しているjsonには「locality」という名前のフィールドは含まれていませんが、タイプフィールドの値の1つとして含まれています。

于 2013-03-02T05:47:48.940 に答える