如何在Json中获取Android / Java中的wunderground API元素

时间:2014-07-08 23:13:23

标签: java android json wunderground

我正在使用Wunderground api获取Android应用的每小时天气预报。我想收到Temp和day等信息。

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对象

1 个答案:

答案 0 :(得分: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。不是数组。

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

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