Check if object exists in JSON
I need to know if an object exists in a JSON string and do different things depending on the existence of that object. If it doesn't exist, I want to omit the object because it throws a NullPonterException. I tried using if but no time ... Can anyone tell me how I can check for the existence of an object?
Thank you in advance!
+3
source to share
4 answers
Try the following:
String jsonString = yourJsonString;
String nameOfObjectInQuestion = "yourObjectInQuestion";
JSONObject json = null;
JSONObject objectInQuestion = null;
try {
json = new JSONObject(jsonString);
objectInQuestion = json.getJSONObject(nameOfObjectInQuestion);
}
catch (JSONException ignored) {}
if (objectInQuestion == null) {
// Stomp your feet
}
else {
// Clap your hands
}
+14
source to share
You can use isNull () function in JSONObjects.
"boolean isNull (string name) Returns true if this object has no mapping for name or has a mapping that is NULL."
JSONObject contact = venueitem.getJSONObject("contact");
if (contact.isNull("formattedPhone") == false)
venue.phone = contact.getString("formattedPhone");
else
{
...
}
Source: http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
+4
source to share
Use JSONObject.has (String).
JSONObject MyObject = null;
if(JSONObject.has("ObjectName")){
MyObject = JSONObject.getJSONObject("ObjectName");
}
if(MyObject != null){
// do stuff
}
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
+2
source to share