检查JSON中是否存在对象

KrL*_*ler 3 android json gson deserialization

我需要知道一个对象是否存在于JSON字符串中,并根据该对象的存在执行不同的操作.如果它不存在,我想省略该对象,因为它抛出NullPonterException.我尝试使用if但没有成功......有人能告诉我如何检查对象的存在?

先感谢您!

Jac*_*ips 14

尝试以下内容:

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
}
Run Code Online (Sandbox Code Playgroud)