0

Here is the code im working with. Im creating a JSONArray with JSONObjects and trying to get back the JSONObjects back and the attributes:

JSONArray:

[
    {
        "test":{
            "page":"Apple",
            "ms":"234"
        }
    },
    {   
        "check":{
            "page":"Apple",
            "ms":"234"
        }
    }
]

JAVA code:

arr1 is JSONArray and contains above data;

for( int i = 0 ; i < arr1.length() ; i++ ){         
    try {
        JSONObject object = arr1.getJSONObject(i);
        //Check whether it is "test"
            JSONObject jo = object.getJSONObject("test");
            System.out.println(jo.getString("page"));
        //check whether it is "check"
            JSONObject jo = object.getJSONObject("check");
            System.out.println(jo.getString("page"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

What i want to know is how to check whether that first JSONObject has specified value and then go to next object. I have commented the place for the IF or SWITCH statement. Please help

Vithushan
  • 503
  • 3
  • 9
  • 34

1 Answers1

2

To check whether some element is present or not use JSONObject.isNull method.

 for( int i = 0 ; i < arr1.length() ; i++ ){         
   try {
       JSONObject object = arr1.getJSONObject(i);
       //Check whether it is "test"
       if( ! object.isNull("test") ){
        // do your stuff 
       }
   } catch (JSONException e) {
        e.printStackTrace();
   }
}
blackSmith
  • 3,054
  • 1
  • 20
  • 37