我正在使用Retrofit库在Android应用程序上工作,无法访问Retrofit返回的某些字段。
我的JSON结构如下:
{
"contacts": [
{
"id": 19,
"name": "some name",
"phone_number": 12345678,
"country": "some country",
"age": 25
}
]
}
我为JSON结构创建的POJO类如下:
public class Contact {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("phone_number")
@Expose
private Integer phoneNumber;
@SerializedName("country")
@Expose
private String country;
@SerializedName("age")
@Expose
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
和我要求答复的班级:
public class Example {
@SerializedName("contacts")
@Expose
private List<Contact> contacts = null;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
,当我尝试使用以下方法访问字段时:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("" + GlobalVariables.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
BaseRestInterface request = retrofit.create(BaseRestInterface.class);
Call<Example > call = request.getContacts();
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Call<Example> call, Response<Example> response) {
loading.dismiss();
assert response.body() != null;
String name = response.body().getContacts().get(0).getName();
int age = response.body().getContacts().get(0).getAge();
}
@Override
public void onFailure(Call<Example> call, Throwable t) {
loading.dismiss();
if(t instanceof IOException) {
Toast.makeText(getContext(), "Connection Problem, Please Try Again Later",
Toast.LENGTH_SHORT, true).show();
}
else
{
Toast.makeText(getContext(), t.getMessage(),
Toast.LENGTH_SHORT, true).show();
}
}
});
我得到一个空值,我在做错什么吗?在调试我的应用程序时收到响应,我只是无法获取值
谢谢。