【问题标题】:How to get json array values in android?如何在android中获取json数组值?
【发布时间】:2013-02-05 13:42:50
【问题描述】:

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

【问题讨论】:

  • 这不是一个有效的 JSON。你确定它不包含花括号:{}
  • @NikitaBeloglazov 看到这个链接maps.googleapis.com/maps/api/geocode/…
  • @NikitaBeloglazov 这是一个 JSON 数组。
  • @DoctororDrive 如何获取这些值。
  • @DoctororDrive 不是。它是 jsong 对象的一部分,但不是有效的 json :)

标签: android json


【解决方案1】:
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();
    }

}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2014-11-25
        • 2019-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多