java - 在 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"
?
解决方案
您可以使用 JACKSON 或 GSON 库使用模型类快速解析 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");
......
}
推荐阅读
- jquery - 如何在不使用 ajax (MVC) 的形式的情况下序列化我的视图模型?
- java - 我注入的 sessionFactory 实例为空
- python - 计算最少可能的步骤来创建之字形阵列
- python-3.x - 如何使用opencv从放置在地面的相机中找到电线的高度?
- java - 将 PowerShell 进程的每个值存储到 Java 对象数组中
- node.js - Dockerize 和重用 NodeJS 依赖
- html - 在同一组件Angular 11中使用多个日期选择器
- php - 是否可以在外部网页上使用 DOM?
- php - 需要在 PHPmailer 附件上提供动态内容
- python - 无法从崩溃中抓取数据。“NoneType”对象没有属性“div”