使用Retrofit从REST获取响应时的NullPoint



我正在使用Retrofit与Android上的REST API进行通信,但是我收到错误NullPointerException,如下所示。我尝试使用邮递员,API 工作正常,我得到了响应。

java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法 'java.util.List ukmutilizer.project.com.ukm_utilizer.model.CheckEmail.getData(('

这是我的活动类

private void sendRequest(String checkEmail){
    ApiInterface apiService =  ApiClient.getClient().create(ApiInterface.class);
    Call<CheckEmail> call = apiService.getEmailStatus(checkEmail);
    call.enqueue(new Callback<CheckEmail>() {
        @Override
        public void onResponse(Call<CheckEmail> call, Response<CheckEmail> response) {
            CheckEmailData emailDataList = response.body().getData();
            Log.d("Numer of Data : ", String.valueOf(response.body().getData()));
        }
        @Override
        public void onFailure(Call<CheckEmail> call, Throwable t) {
            Toast.makeText(CheckEmailPage.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
            Log.e("Error Retrofit : ", String.valueOf(t));
        }
    });

这是 API 接口

public interface ApiInterface {
@POST("users/check_status")
Call<CheckEmail> getEmailStatus(@Body String email);
}

这是改造实例

`public class ApiClient {
public static final String BASE_URL = "https://f49d9d29-8471-4126-95b0-1ec3d18eda94.mock.pstmn.io/v1/";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();

    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
   }
}`

这是 JSON 响应

{
"code": 1000,
"message": "OK",
"data": {
    "id": "1",
    "email": "test@gmail.com",
    "status": "1",
    "name": "test",
    "category": "2"
  }
}

这是波乔

`public class CheckEmail {

    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("data")
    @Expose
    private CheckEmailData data;
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public CheckEmailData getData() {
        return data;
    }
    public void setData(CheckEmailData data) {
        this.data = data;
    }
}`

检查电子邮件数据 POJO

`public class CheckEmailData {
@SerializedName("id")
@Expose
private String id;
@SerializedName("email")
@Expose
private String email;
@SerializedName("status")
@Expose
private String status;
@SerializedName("name")
@Expose
private String name;
@SerializedName("category")
@Expose
private String category;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getStatus() {
    return status;
}
public void setStatus(String status) {
    this.status = status;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
}`

你只有一个数据,json 对象,来自 json 响应上的 api

{
"code": 1000,
"message": "OK",
"data": {
    "id": "1",
    "email": "test@gmail.com",
    "status": "1",
    "name": "test",
    "category": "2"
  }
}

但是,您将数据声明为 List 对象,它期望以 JSON 数组格式显示上述data

您应该将列表更改为

@SerializedName("data")
@Expose
private CheckEmailData data;

我相信会没事的。

在该 JSON 中,"data"是一个对象,而不是一个数组。在CheckEmail类中,将private List<CheckEmailData> data;更改为private CheckEmailData data;

在访问响应中的数据之前,应检查响应本身是否正常。

@Override
public void onResponse(Call<CheckEmail> call, Response<CheckEmail> response) {
    if(response.isSuccessfull()){
        //if you are sure that when the response is OK the list is not null
        //you can leave this line below to hide the lint warning, otherwise
        //before accessing the list with getData() check that response.body() is not null
        //noinspection ConstantConditions
        List<CheckEmailData> emailDataList = response.body().getData();
        Log.d("Numer of Data : ", String.valueOf(emailDataList.size()));
        for (CheckEmailData emailData : emailDataList){
            Log.d("Successfull : ", String.valueOf(emailData.getStatus()));
        }
    } else {
        //you got an error response, handle it
    }
}

我已经解决了问题

我在界面上添加了标题,如下所示

public interface ApiInterface {
@Headers({
        "Content-Type:application/x-www-form-urlencoded"
})
@POST("v1/users/check_status")
Call<CheckEmail> getEmailStatus(@Body String email);
}

最新更新