user13438351
user13438351

Reputation:

How can I check if object of JSON array contains number with certain name in Android Java?

I have this JSON array and I need to check every object of it if it has a "rain" number as 1st object does. How can I implement it in Java, Android? I am making an android app that needs to analyze if it rains someday.

 "daily": [
        {
            "dt": 1597730400,
            "sunrise": 1597705822,
            "sunset": 1597758442,
            "temp": {
                "day": 299.15,
                "min": 288.84,
                "max": 299.15,
                "night": 288.84,
                "eve": 298.91,
                "morn": 299.15
            },
            "feels_like": {
                "day": 291.47,
                "night": 287.34,
                "eve": 293.53,
                "morn": 291.47
            },
            "pressure": 997,
            "humidity": 27,
            "dew_point": 278.72,
            "wind_speed": 9.52,
            "wind_deg": 200,
            "weather": [
                {
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10d"
                }
            ],
            "clouds": 100,
            "pop": 0.86,
            "rain": 1.03,
            "uvi": 4.86
        }

Upvotes: 0

Views: 204

Answers (2)

Tal Mantelmakher
Tal Mantelmakher

Reputation: 1002

String yourJSONString; //should hold the JSON you have 
JSONArray c = JSONArray(yourJSONString);
    for (int i = 0 ; i < c.length(); i++) {
        JSONObject obj = c.getJSONObject(i);
        if(obj.has("rain")){
          //object has "rain" property
        }
        else{
          //object doesnt have "rain" property
        }
    }

Upvotes: 1

Abhimanyu
Abhimanyu

Reputation: 14827

You would like to check if "rain" attribute is returned in the response.

To do so, follow these steps:

  1. Create a class for the object in the JSON array.
  2. Use Gson or any other JSON library in Android to convert the fetched JSON into the created class object.
  3. Then check if rain is not null and if rain is not equal to 0 to confirm rain attribute is present in the JSON objects in the array.

Upvotes: 1

Related Questions