首页 > 解决方案 > 在 Android 上通过 GSON 从嵌套 JSON 数组中获取价值?

问题描述

上下文:我无法从 OpenWeatherMap 的 API 通过 Android 返回的 JSON 中获取值。

我的 JSON 看起来像这样:

{"coord":{"lon":-78.32,"lat":38.55},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":269.05,"feels_like":265.34,"temp_min":267.59,"temp_max":270.37,"pressure":1010,"humidity":78},"visibility":10000,"wind":{"speed":1.25,"deg":293},"clouds":{"all":25},"dt":1607493640,"sys":{"type":3,"id":2006561,"country":"US","sunrise":1607516385,"sunset":1607550737},"timezone":-18000,"id":4744896,"name":"Ashbys Corner","cod":200}

它存储在来自 URL 的JsonObject(GSON 的一部分,不要与 混淆JSONObject)中,如下所示:

URLConnection requestWeather = weatherUrl.openConnection();
requestWeather.connect(); // connect to the recently opened connection to the OpenWeatherMaps URL
JsonElement parsedJSON = JsonParser.parseReader(new InputStreamReader((InputStream) requestWeather.getContent())); //Convert the input stream of the URL into JSON
JsonObject fetchedJSON = parsedJSON.getAsJsonObject(); // Store the result of the parsed json locally as a json object

问题:我想从 JSON 中获取与关联的值"main"(在这种情况下应该是“云”)。

尝试的解决方案:我试图像这样获取 main 的值:

String weatherType = fetchedJSON.get("weather").getAsString();

但这会引发java.lang.UnsupportedOperationException: JsonObject异常。

问题:我如何获得 的值"main"

标签: javaandroidjsonhttpgson

解决方案


您可以使用 JACKSON 或 GS​​ON 库使用模型类快速解析 Json 数据。JACKSON 和 GSON 专用于处理(序列化/反序列化)JSON 数据。

通过 GSON 进行原始解析

JsonObject fetchedJSON = parsedJSON.getAsJsonObject();
//weather is an array so get it as array not as string
JsonArray jarray = fetchedJSON.getAsJsonArray("weather");
// OR you use loop if you want all main data
jobject = jarray.get(0).getAsJsonObject();
String main= jobject.get("main").getAsString();

虽然如果你想要原始解析,那么你可以这样做::

JSONObject obj = new JSONObject(yourString);

JSONArray weather = obj.getJSONArray("weather");
for (int i = 0; i < arr.length(); i++)
{
String main= arr.getJSONObject(i).getString("main");
......
}

推荐阅读