简体   繁体   中英

Null pointer when trying to access POJO attribute

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());
        }
    });
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());
        }

    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM