2013-02-24 17 views
1

我想從以下JSON我試圖從JSON輸出到字符串獲取地點名稱,並把它傳遞給一個變量

http://maps.googleapis.com/maps/api/geocode/json?latlng=18.486096,73.802027&sensor=false特定地址,該地址returs JSON獲取地點名稱。我正在開發一個Android應用程序來使用API​​反轉地理編碼。

這是下面的代碼..

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

回答

0

爲了解析JSON,你做錯了。首先url返回JSONObject,其中包含JSONArray結果」和字段「」狀態「。 所以,你應該取消註釋以下行:

JSONObject Strjson = new JSONObject(readUserFeed); 

,我建議你檢查狀態字段的值,就看你是OK,它具有數據是這樣的:

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

然後得到使用JSONArray

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

,並通過每個迭代JSONObject獲取字段值你requir e,但是事情是你得到的json不包含名稱爲「locality」的字段,但包含它作爲type字段的值之一。

相關問題