我正在使用Retrofit来解析API。
我使用给定的网址
https://api.androidhive.info/contacts/
我生成了POJO类。
public class MyPojo {
private List<Contacts> contacts;
public List<Contacts> getContacts() {
return contacts;
}
public void setContacts(List<Contacts> contacts) {
this.contacts = contacts;
}
@Override
public String toString() {
return "ClassPojo [contacts = " + contacts + "]";
}
}
联系人:
public class Contacts
{
private String id;
private Phone phone;
private String address;
private String email;
private String name;
private String gender;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public Phone getPhone ()
{
return phone;
}
public void setPhone (Phone phone)
{
this.phone = phone;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getGender ()
{
return gender;
}
public void setGender (String gender)
{
this.gender = gender;
}
@Override
public String toString()
{
return "ClassPojo [id = "+id+", phone = "+phone+", address = "+address+", email = "+email+", name = "+name+", gender = "+gender+"]";
}
}
然后在界面中,我补充说,
public interface ApiInterface {
@GET("/contacts")
Call<MyPojo> getJSON();
}
然后在MainActivity中,
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.androidhive.info")
.addConverterFactory(GsonConverterFactory.create())
.build();
final ApiInterface request = retrofit.create(ApiInterface.class);
Call<MyPojo> call = request.getJSON();
call.enqueue(new Callback<MyPojo>() {
@Override
public void onResponse(Call<MyPojo> call, Response<MyPojo> response) {
Log.e("response", response.errorBody().toString());
MyPojo pojo = response.body();
List<Contacts> contactses = pojo.getContacts();
for (int i = 0; i < contactses.size(); i++) {
Log.e("contacsses", contactses.get(i).getAddress());
Toast.makeText(MainActivity.this, contactses.get(i).getName(), Toast.LENGTH_SHORT)
.show();
}
}
@Override
public void onFailure(Call<MyPojo> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT)
.show();
}
});
}
}
我收到Toast消息失败。
在我犯错误的地方,我很无能为力。请纠正我的错误。
由于