anonymous
anonymous

Reputation: 1330

Check if an 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 omit the object because it throws NullPonterException. I've tried using if but no success... Can someone tell me how can I check the existence of an object?

Thank you in advance!

Upvotes: 4

Views: 14845

Answers (4)

Lachlan Ennis
Lachlan Ennis

Reputation: 1128

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)

Upvotes: 3

roxX
roxX

Reputation: 156

You can use isNull() function on JSONObjects.

"boolean isNull(String name) Returns true if this object has no mapping for name or if it has a mapping whose value 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)

Upvotes: 4

DiegoSalas
DiegoSalas

Reputation: 43

Or.. more concise...

myJSONObject.isNull("myfield")?"":myJSONObject.getString("myfield")

Upvotes: 1

Jacob Phillips
Jacob Phillips

Reputation: 9264

Try something like 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
}

Upvotes: 15

Related Questions