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\"
you could JSONObject#has
, providing the key
as input and check if the method returns true
or false
. You could also
use optString
instead of getString
:
Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists
Json has a method called containsKey()
.
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {}
and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0)
and do your things.
Happy learning!
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
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.