Q: NullPointerException if the JSON contains null I am having a little issue.
When I use JSON path to extract a value from a DTO like so:
public String recipientEmail() {
    String email = validatableResponse.extract().jsonPath().get("email[0]").toString();
    return email;
}

If that DTO contains a value like:
email: "test@gmail.com"

It works fine and outputs this value. However, if the value is null like so:
email: null

Then it gives me a NullPointerException. How can I fix this and be able to retrieve the null?
Thanks.

A: If you want to have your email String contain the value "null", then you should use the String.valueOf() method instead of the .toString() method. The difference is that String.valueOf() will return the String "null", where .toString() will throw a NullPointerException, instead.
So your line could look like this:
String email = String.valueOf(validatableResponse.extract().jsonPath().get("email[0]"));


This post explains it well.

A: What value should be returned, if your value is null?
At first I´d set the String to the value, wich should be returned when the result is null. Then I´d try to set the new value. If this fails, the method will return the value that was set first. Try and catch is used to avoid a crash when the NullPointer is thrown.
public String recipientEmail() {
String email="";
try{
    email = validatableResponse.extract().jsonPath().get("email[0]").toString();
}catch(NullPointerException ex){
ex.printStacktrace();
}
    return email;
}


A: .toString() method is inside an object. If your object is a null then the jvm cannot find the toString() method. So NullPointerException.
Try,
String email = validatableResponse.extract().jsonPath().get("email[0]");

if(email == null){
   email = "null";
}else{
   email = email.toString();
}

