Reputation: 1459
I'm using the org.json.JSONObject
(and parser) in an Android app to parse a JSON feed. Which is the best way to determine if a property exists or not in one of the objects returned?
Say I have a JSON feed including "News". Some of the news have a property called "UnpublishDate" (which is the date the news in question is no longer active), while some of the news don't have this property.
The best solution I've come up with (though not implemented yet) is to simply have a "try-catch" around the theJSONObject.get("UnpublishDate")
- do you know of any better solution (that is more graceful when the class scales to several "optional" properties in the JSON feed)?
Upvotes: 45
Views: 38724
Reputation: 26271
You might use the JSONObject
function has
:
if(myJSONObject.has("UnpublishDate")) {
//it has it, do appropriate processing
}
Upvotes: 133