Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would to refer to the description field in the weather array using the getDescription function

"weather": [
    {
        "id": 600,
        "main": "Snow",
        "description": "light snow",
        "icon": "13d"
    }
],

public String getDescription() {
String description = String.valueOf(obj.getJSONArray("weather"));
String jObj = String.valueOf(obj.getJSONObject("description"));
return jObj;

How to write correctly getDescription functions to get the description value from the Weather array?

question from:https://stackoverflow.com/questions/66067015/how-to-reference-a-json-array-using-an-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to get the weather Array from obj, then retrieve the item you want from the array, then the description.

public String getDescription() {
    JsonArray weatherArray = obj.getJsonArray("weather");
    JsonObject weatherObject = weatherArray.getJsonObject(0);
    return weatherObject.getString("description");
}

This method is not validating anything for simplicity, but keep in mind and implement the appropriate checks for when any of those objects is null or if the weather array is empty.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...