1

我正在使用 Wunderground api 获取 Android 应用程序的每小时天气预报。我想接收诸如温度和日期之类的信息。

Json 的一个例子是:

"hourly_forecast": [
    {
    "FCTTIME": {
    "hour": "11","hour_padded": "11","min": "00","min_unpadded": "0","sec": "0","year": "2014","mon": "7","mon_padded": "07","mon_abbrev": "Jul","mday": "8","mday_padded": "08","yday": "188","isdst": "1","epoch": "1404842400","pretty": "11:00 AM PDT on July 08, 2014","civil": "11:00 AM","month_name": "July","month_name_abbrev": "Jul","weekday_name": "Tuesday","weekday_name_night": "Tuesday Night","weekday_name_abbrev": "Tue","weekday_name_unlang": "Tuesday","weekday_name_night_unlang": "Tuesday Night","ampm": "AM","tz": "","age": "","UTCDATE": ""
    },
    "temp": {"english": "61", "metric": "16"},
    "dewpoint": {"english": "56", "metric": "13"},
    "condition": "Partly Cloudy",
    "icon": "partlycloudy",
    "icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif",
    "fctcode": "2",
    "sky": "58",
    "wspd": {"english": "7", "metric": "11"},
    "wdir": {"dir": "SW", "degrees": "232"},
    "wx": "Partly Cloudy",
    "uvi": "9",
    "humidity": "83",
    "windchill": {"english": "-9999", "metric": "-9999"},
    "heatindex": {"english": "-9999", "metric": "-9999"},
    "feelslike": {"english": "61", "metric": "16"},
    "qpf": {"english": "0", "metric": "0"},
    "snow": {"english": "0", "metric": "0"},
    "pop": "2",
    "mslp": {"english": "29.92", "metric": "1013"}
    }

它似乎在一个数组中,但是当我尝试以下操作时,它出现了一个不是 json 对象的错误。

String row = rootArray.getAsJsonObject().get("sky").getAsString(); 

** 编辑 ** 我能够让它与代码一起工作

String skyText = rootobj.getAsJsonObject().getAsJsonArray("hourly_forecast").get(0).getAsJsonObject().get("sky").getAsString(); 

rootobj 是我的 json 对象

4

1 回答 1

0

您发布的 JSON 不是数组。相反,它是一个具有名为“hourly_forecast”的键的对象,并且该键指向一个数组值。

Key                Value
hourly_forecast    JSONArray

因此,如果您的 JSON 在名为 的字符串中wundergroundData,您将访问“sky”值,如下所示:

JSONObject json = new JSONObject(wundergroundData);
String skyText = json.getJSONArray("hourly_forecast").get(0).getString("sky");

或者,为了更密切地遵循您发布的示例,我想这样的事情也会起作用:

String row = rootArray.getAsJsonObject().getJSONArray("hourly_forecast").get(0).getString("sky"); 

虽然,您可能想要重命名该rootArray变量,因为根实际上是一个 JSONObject。不是数组。

如果这不起作用,请发布您的完整 JSON,我可以准确地告诉您使用它需要做什么。现在,您在开头缺少花括号或方括号,以及 JSON 的结尾。我在这里假设您的 JSON 以花括号开头。如果它以方括号开头,那么您将需要类似以下代码的内容:

String row = rootArray.get(0).getJSONArray("hourly_forecast").get(0).getString("sky"); 
于 2014-07-08T23:25:30.030 回答