Retrofit2: How to correctly check the authenticity of response.body ()?

Since the version retrofit2.retrofit:2.3.0, I get warnings NullPointerExceptionon response.body()even when checking the body for nullbefore:

Picture

Method invocation 'getCar()' may produce 'java.lang.NullPointerException'

In the change log for there 2.3.0was an entry related to null checks:

The newly updated version now uses @Nullable to annotate all possible null values. [...] We use @ParametersAreNonnullByDefault, and all parameters and return types are never null unless explicitly annotated @Nullable.

Is that what the intended behavior is? In my point of view it response.body()should be unchanged, so my check in Picture 1 should not show a warning.

This is not a question of NullPointerExceptions- about how to properly handle Retrofit2 responses. In order to not have warnings at the moment, I should do something like this:

if(response != null) {
    CarResponseBody body = response.body();
    if (body != null && body.getCar() != null){
        CarResponse car = body.getCar();
    }
}

Lots of code to just check if there is a valid answer ...

+6
source share
3 answers

Is this the intended behavior?

If you are checking out JavaDoc Response<T>you can read

@Nullable public T body () From the deserialized response body of a successful response.
Javadoc: response

It is body()not expected nullif the answer was successful. To test success, you have isSuccessful()which

true, () [200..300).

, @Nullable , null , . , .

IDE - , .

body() null lint .

response.body() , 1 .

. , body() , , .

T res1 = response.body(); // could be null
T res2 = response.body(); // ...maybe still null?

Lint - , , NPE. @Nullable, , null, , .

// does response return the same value twice? who knows?
response.body() != null && response.body().getCar() != null

, , lint, .

, , null - null , lint .

CarResponseBody body = response.body(); // assign body() to a local variable
if (body != null && body.getCar() != null) { // variable is not null
    CarResponse car = body.getCar(); // safe to access body, car is also not null
    // everything is fine!
}

, ?

. @Nullable - , null, , null , lint NullPointerExceptions.

null, null , .

Car car = response.getBody(); // car could be null
if(car != null) {
  // car will never be null
}

/

, , , .

CarResponseBody body = response.body();
Car car = body.getCar()

, , *ResponseBody . , . Jake Wharton

RxJava Retrofit, . , , Rx-.

+13

isValid() hasResults() WhateverResponse

boolean isValid(){
return getCar() != null && getWheel() != null && somethingElse
}

if(response.isValid()){
//do your other if's
}

. errorBody() null retrofit2.Callback onFailure() ,

+1

try it

 if (response != null) {CarResponseBody body= new CarResponseBody(); if (response.raw().code() == 200 && response.body()!=null) {
body = response.body();if(body.getCar()!=null){ CarResponse car =body.getCar()}}}
0
source

All Articles