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)?
Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().
One easy way would be to use if check in data["players"]. __str__() which will convert value to a string and search for the match. If you want to make sure that check value only checks for the steam64 values, you can write a simple function that will iterate over all "players" and will check their "steam64" values.
You might use the JSONObject
function has
:
if(myJSONObject.has("UnpublishDate")) { //it has it, do appropriate processing }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With