How to check if a json key exists?

Adam Varhegyi picture Adam Varhegyi · Jul 5, 2013 · Viewed 326.1k times · Source

So, I get some JSON values from the server but I don't know if there will be a particular field or not.

So like:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited"
}

And sometimes, there will be an extra field like:

{ "regatta_name":"ProbaRegatta",
  "country":"Congo",
  "status":"invited",
  "club":"somevalue"
}

I would like to check if the field named "club" exists so that at parsing I won't get org.json.JSONException: No value for club

Answer

PX Developer picture PX Developer · Jul 5, 2013

JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Returns true if this object has a mapping for name. The mapping may be NULL.