尝试访问 POJO 属性时的空指针

Null pointer when trying to access POJO attribute

我正在使用 Retrofit 2 来消耗 JSON API,我有以下 JSON 结构

{
    "data": {
        "id": 1,
        "name": "Josh"
    }
}

我的 User POJO 看起来像:

public class User {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

还有我的用户界面

@GET("/api/v1/me")
Call<User> me();

但是当我尝试做 response.body().getName() 时,我得到一个空指针异常。

发出请求的代码

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

    }

您应该按如下方式创建 POJO 类:

json 的 POJO 响应:

public class User {


    private Data data;


    public Data getData() {
        return data;
    }


    public void setData(Data data) {
        this.data = data;
    }

}

内部数据的 POJO:

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

}

比使用 response.body().getData().getName() 访问名称作为响应。