Check if JSONObject key exists

穿精又带淫゛_ 提交于 2021-01-27 13:53:52

问题


I'm making api calls to a back-end who always has a JSONArray series and sometimes has a JSONArray places. In the code below, I am trying to write an if statement that says, whenever there is no places array, make another http request. However, I am not getting a nullpointer, it just throws a JSON Exception saying there is no value for places. What can I put as the terminating condition, for when places has no value? I have tried places == null and that hasn't worked.

try{
    JSONArray places = passingObject.getJSONArray("places");
    JSONArray series = passingObject.getJSONArray("series");

    if(some condition){
       //do something else
    }
}catch(JSONException e){
    Log.d("JSON EXCEPTION" e.getMessage());
}

回答1:


Or you can use http://www.json.org/javadoc/org/json/JSONObject.html#optJSONArray(java.lang.String)

JSONArray places = passingObject.optJSONArray("places");
if(places == null){...}

optJSONArray(); It returns null if there is no such key, or if its value is not a JSONArray.




回答2:


Check if the object has a key called places.

if (passingObject.has("places") {
    JSONArray places = passingObject.getJSONArray("places");
} else {
    askServerAgain();
}


来源:https://stackoverflow.com/questions/32470315/check-if-jsonobject-key-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!