通过android上的gson从嵌套json数组中获取值?

1hdlvixo  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(440)

这个问题在这里已经有答案了

如何在android中使用gson解析json(5个答案)
上个月关门了。
上下文:我很难从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}

它存储在 JsonObject (gson的一部分,不要与 JSONObject )从这样的url:

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

问题:我想获取与 "main" 在json之外(在本例中应该是“clouds”)。
尝试解决方案:我尝试如下方式获取main的值: String weatherType = fetchedJSON.get("weather").getAsString(); 但这件事 java.lang.UnsupportedOperationException: JsonObject 例外。
问题:如何获得 "main" ?

wr98u20j

wr98u20j1#

您可以使用jackson或gson库使用model类快速解析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");
......
}

相关问题