android - 如何使用 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();
}
});
我想检查内部响应是否为空,谢谢
解决方案
在将 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...
}
}
推荐阅读
- javascript - 反应悬念不起作用,我不知道为什么
- c++ - pugixml 节点移动方法如何工作?
- c++ - 如何在不通过 using 声明暴露字符串的情况下显式调用 std::string 析构函数?
- java - PreparedStatement 的 .executeUpdate() 方法挂起,不给出异常,或超时
- ms-word - MS Word:将纯文本引用转换为链接引用
- django - 'django_1 | 运行 docker-compose up 后没有要连接的端口 [s]
- javascript - WebGL OpenGL 形状的绘制顺序错误
- winapi - 在 windows 中关闭显示器
- firebase - 流和 firebase 状态不佳的问题:DocumentSnapshotPlatform 中不存在字段
- javascript - node.js eventEmitter setImmediate vs. async