我使用 Retrofit simple
我在调用"<"EmployeesModel">"
MyApplictaion 运行时显示停止应用程序消息 我的来源:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.mocky.io/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
和服务器源:
//Server
Call<EmployeesModel> call = service.getEmployees();
call.enqueue(new Callback<EmployeesModel>() {
@Override
public void onResponse(Call<EmployeesModel> call, Response<EmployeesModel> response) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<EmployeesModel> call, Throwable t) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
还有我的界面源
public interface APIService {
@GET("569ce520110000fb2dce7655")
Call<EmployeesModel> getEmployees();
}
最佳答案
将您的 EmployeesModel
模型替换为以下模型,并添加另一个名为 Employee
的模型类
EmployeesModel.java
public class EmployeesModel {
@SerializedName("employees")
@Expose
private List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
Employee.java
public class Employee {
@SerializedName("firstName")
@Expose
private String firstName;
@SerializedName("lastName")
@Expose
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
然后尝试像这样访问数据(示例显示访问 key - firstName
)
@Override
public void onResponse(Call<EmployeesModel> call, Response<EmployeesModel> response) {
Toast.makeText(MainActivity.this, "OK, firstName :"+response.body().getFirstName(), Toast.LENGTH_SHORT).show();
}
关于android - Retrofit 中的错误 call.enqueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50933908/