3

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());
}
4

2 に答える 2

2

または、 http://www.json.org/javadoc/org/json/JSONObject.html#optJSONArray(java.lang.String)を使用できます 。

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

optJSONArray();そのようなキーがない場合、またはその値が JSONArray でない場合は null を返します。

于 2015-09-09T03:15:15.297 に答える