45

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)?

1 Answer 1

133

You might use the JSONObject function has:

if(myJSONObject.has("UnpublishDate")) {
    //it has it, do appropriate processing
}
6
  • it is to check if that object contains key, but how to find it contains value for it? Dec 19, 2016 at 13:26
  • @ShylendraMadda if it has a key, it has a value. It's up to you to decide whether the value is acceptable
    – james
    Dec 19, 2016 at 13:45
  • how do I check it contains value or not?? Dec 19, 2016 at 13:47
  • @ShylendraMadda how do you define "contains value"? not null? my previous comment should give you the answer...
    – james
    Dec 19, 2016 at 13:48
  • but here in my case I have key but there is no value, so how to find it? It doesn't contains value with that key? Dec 20, 2016 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.