当json响应值为空时,我得到以上错误
{
"restaurant_area_min_order":null,
"restaurant_id":null
}.
上面的错误出现在try catch块中。当restaurant_area_min_order和restaurant_id中有值时,该函数正常工作且没有错误。如何检查响应数据是否为空并继续执行该函数而没有任何错误?
这是我的代码。
private void getAreaMinOrders()
{
for(int i = 0; i < Utils.cart_restaurants.size(); i++)
{
RestaurantModel restaurant = Utils.cart_restaurants.get(i);
String restaurant_id = restaurant.getId();
String url = LinksConstants.BASE_URL + LinksConstants.CHECK_MINIMUM_ORDER;
RequestParams params = new RequestParams();
params.put("restaurant_id", restaurant_id);
params.put("area_id", city_id);
NetworkRestClient.post(url, params, new JsonHttpResponseHandler()
{
@Override
public void onStart()
{
super.onStart();
progressActivity.showLoading();
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
super.onSuccess(statusCode, headers, response);
try
{
if (response != null)
{
String restaurant_id = response.getString("restaurant_id");
String rest_area_min_order = null;
if(rest_area_min_order != null)
{
rest_area_min_order = response.getString("restaurant_area_min_order");
}
HashMap<String, Object> items_hash = (HashMap<String, Object>) rest_cart_hash.get(restaurant_id);
items_hash.put("rest_area_min_order", rest_area_min_order);
}
progressActivity.showContent();
}
catch (Exception ex)
{
GSLogger.e(ex);
showError();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable throwable)
{
super.onFailure(statusCode, headers, errorResponse, throwable);
showError();
if (AppConstants.DEBUG_MODE)
showToast(errorResponse);
}
}); //end of NetworkRestClient.post
} //end of for
}
答案 0 :(得分:1)
您可以使用JSONObject.isNull()
方法检查是否为空。
response.isNull("your_key"); // returns true if the value of that key is null
但是根据您发布的详细信息,您的代码中的HashMap<String, Object> items_hash
似乎为空。
添加空检查:
if(restaurant_id != null) {
HashMap<String, Object> items_hash = (HashMap<String, Object>) rest_cart_hash.get(restaurant_id);
items_hash.put("rest_area_min_order", rest_area_min_order);
}