Reputation: 4302
I am using Retrofit 2 to consume an JSON API, I have the following JSON structure
{
"data": {
"id": 1,
"name": "Josh"
}
}
My User
POJO looks like:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And my User interface
@GET("/api/v1/me")
Call<User> me();
But I when I try and do response.body().getName()
I get a null pointer exception.
The code which is making the request
UserService userService = ServiceGenerator.createService(UserService.class)
Call<User> call = userService.me();
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getName().toString());
}
}
@Override
public void onFailure(Throwable t) {
Log.i("hello", t.getMessage());
}
});
Upvotes: 2
Views: 1284
Reputation: 5186
public class Data {
private User data;
public String getData() {
return data;
}
public void setName(User data) {
this.data = data;
}
}
Access it like this
public void onResponse(Response<Data> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getData().getName().toString());
}
}
Upvotes: 1
Reputation: 370
You should create the POJO classes as follows:
POJO for json response:
public class User {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
POJO for internal Data:
public class Data {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Than use response.body().getData().getName() to access name in response.
Upvotes: 1