【发布时间】:2021-03-20 12:51:45
【问题描述】:
上下文:我无法从 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" 关联的值(在本例中应该是“Clouds”)。
尝试的解决方案:我试图像这样获取 main 的值:
String weatherType = fetchedJSON.get("weather").getAsString();
但这会引发java.lang.UnsupportedOperationException: JsonObject 异常。
问题:如何获得"main"的值?
【问题讨论】:
-
main是一个JsonObject本身,首先你使用JsonObject main =fetchedJSON.getAsJsonObject("main")获得 main ,然后你可以获得 main 的内部属性。如果你使用 Gson,为什么还要手动解析? -
嗯,如果“main”嵌套在“weather”中,我可以在“main”上调用“getAsJsonObject”吗?
-
老实说,我发现你所链接的问题的答案有点令人困惑。
-
我觉得更令人困惑的是,这个问题与 GSON 没有丝毫关系。
-
它使用 GSON 方法/对象,如“JsonElement、JsonObject、JsonParser”等。我怀疑 GSON 的各种 get 方法之一是解决我的问题的方法。
标签: java android json http gson