首页 > 解决方案 > 如何使用 Retrofit 识别来自服务器的 JSON 响应数据是否为空?

问题描述

我正在从服务器检索数据列表,以使用改造显示到 android 中的 recyclerview 中。
检索工作正常,显示调用的数据,没有问题。

但问题是,我想检查我得到的数据是否为空,因为我想从这个检查中做一些动作。

我已经尝试过这段代码,但它只检查请求是否成功,而不是它从服务器带来的 JSON 数据内容。

getData.enqueue(new Callback<Model>() {
@Override
public void onResponse(Call<Model> call, Response<Model> response) {

if (response.body() != null){
Toast.makeText(getApplicationContext(), "Data is not empty", Toast.LENGTH_LONG).show();
} else {
// want to do some action here after the checking
Toast.makeText(getApplicationContext(), "Data isempty", Toast.LENGTH_LONG).show();
}
someList = new ArrayList<ModelItem>();
someList= response.body().getItem();
adapter= new Adapter(getApplicationContext(), someList);

recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

@Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.error_connection), Toast.LENGTH_LONG).show();
}
});

我想检查内部响应是否为空,谢谢

标签: androidretrofitretrofit2

解决方案


在将 Json 映射到 POJO 之前,请使用以下代码。

String response = basicResponse.getResponse();
if(response!=null){
   String responseBody = response.body();
   if(!responseBody.isEmpty()){
      // non empty response, you can map Json via Gson to POJO classes...

   }
   else{
       // empty response...
   }
}

推荐阅读