0

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.

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Pristin
  • 175
  • 1
  • 2
  • 13
  • 2
    The problem is that you are calling `toString` without checking if you have valid value. – NiVeR Sep 14 '18 at 13:56

3 Answers3

2

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.

0xCursor
  • 2,242
  • 4
  • 15
  • 33
0

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;
}
Don
  • 13
  • 5
0

.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();
}
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80