6

JSON 响应值如下所示"types" : [ "sublocality", "political" ]。如何获取类型的第一个值或如何获取单词 sublocality?

4

3 回答 3

16
String string = yourjson;

JSONObject o = new JSONObject(yourjson);
JSONArray a = o.getJSONArray("types");
for (int i = 0; i < a.length(); i++) {
    Log.d("Type", a.getString(i));
}

如果您只解析上面提供的行,这将是正确的。请注意,要从 GoogleMaps 地理编码访问类型,您应该得到一个结果数组,而不是 address_components,然后您可以访问对象 components.getJSONObject(index)。

这是一个仅解析 formatted_address 的简单实现——我在项目中需要的。

private void parseJson(List<Address> address, int maxResults, byte[] data)
{
    try {
        String json = new String(data, "UTF-8");
        JSONObject o = new JSONObject(json);
        String status = o.getString("status");
        if (status.equals(STATUS_OK)) {

            JSONArray a = o.getJSONArray("results");

            for (int i = 0; i < maxResults && i < a.length(); i++) {
                Address current = new Address(Locale.getDefault());
                JSONObject item = a.getJSONObject(i);

                current.setFeatureName(item.getString("formatted_address"));
                JSONObject location = item.getJSONObject("geometry")
                        .getJSONObject("location");
                current.setLatitude(location.getDouble("lat"));
                current.setLongitude(location.getDouble("lng"));

                address.add(current);
            }

        }
    catch (Throwable e) {
        e.printStackTrace();
    }

}
于 2013-02-05T13:53:46.973 回答
1

您应该解析该 JSON 以获取这些值。您可以在 Android 中使用 JSONObject 和 JSONArray 类,也可以使用 Google GSON 之类的库从 JSON 中获取 POJO。

于 2013-02-05T13:51:48.020 回答
1

我会坚持你使用 GSON。我创建了一个用于解析相同地图响应的演示。您可以找到完整的演示here。此外,我还创建了一个全局 GSON 解析器类,可用于轻松解析 JSON 格式的任何响应。

于 2013-02-05T13:53:54.977 回答