我正在使用改造从服务器检索数据列表以显示到 android 中的 recyclerview 中。
检索工作正常,显示调用的数据没有问题。
但问题是,我想检查我得到的数据是否为空,因为我想从这个检查中做一些动作。
我已经尝试过这段代码,但它一直在检查 only 请求是否成功,not 它从服务器带来的 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...
}
}
首先检查响应的验证,然后检查它的主体,然后在那里做剩下的工作:
@Override
public void onResponse(Call<Model> call, Response<Model> response) {
if ( response.body() != null){
someList = new ArrayList<ModelItem>();
someList= response.body().getItem();
adapter= new Adapter(getApplicationContext(), someList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else {
// want to do some action here after the checking
Toast.makeText(getApplicationContext(), "Data isempty", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.error_connection), Toast.LENGTH_LONG).show();
}
});
这可能对你有帮助。
@Override
public void onResponse(Call<String> call, Response<String> response) {
String responseBody = response.body();
if(!responseBody.isEmpty()){
// Create here Json via Gson to POJO classes...
try {
Gson gson = new Gson();
Type type = new TypeToken<List<Model>>() {
}
.getType();
objModel= gson.fromJson(responseBody, type);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
else{
// empty response...
}
}
@Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.error_connection), Toast.LENGTH_LONG).show();
}
});
您将无法将 response.body() 分配给 String - 您将需要对其调用 string 方法,例如:
String responseBody = response.body().string();