Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to determine if value exists in JSON feed

Tags:

java

json

android

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

like image 904
Manne W Avatar asked Feb 28 '11 16:02

Manne W


People also ask

How do you check if a key exists in JSON object and get its value?

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().

How do you check if a value exists in a JSON string in Python?

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.


1 Answers

You might use the JSONObject function has:

if(myJSONObject.has("UnpublishDate")) {     //it has it, do appropriate processing } 
like image 166
james Avatar answered Sep 23 '22 00:09

james