Check if an object exists in JSON
android, deserialization, gson, json
Solution
Try something like the following:
String jsonString = yourJsonString;
String nameOfObjectInQuestion = "yourObjectInQuestion";
JSONObject json = null;
JSONObject objectInQuestion = null;
try {
json = new JSONObject(jsonString);
objectInQuestion = json.getJSONObject(nameOfObjectInQuestion);
}
catch (JSONException ignored) {}
if (objectInQuestion == null) {
// Stomp your feet
}
else {
// Clap your hands
}
Problem
I need to know if an object exists in a JSON string and do different things depending on the existence of that object. If it doesn't exist, I want omit the object because it throws NullPonterException. I've tried using if but no success... Can someone tell me how can I check the existence of an object? Thank you in advance!