I have my own object when there is no value it is coming as "NULL" in a string from downstream and it is failing while converting to java object in ObjectMapper
class Test
private String value1;
private String value2;
.... getters and setters.
Json Response is
{"Test": "NULL"}
How I can handle this in java Error message is :
** error : com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.test.Test
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('NULL') **
This is how I am converting json to java
ResponseEntity<String> responseEntity = getDownstreamResponse(id);
ObjectMapper mapper = new ObjectMapper();
Test test = mapper.readValue(responseEntity.getBody(), Test.class);
Inside the body of:
ResponseEntity<String> responseEntity = getDownstreamResponse(id);
... you will have:
{"Test": "NULL"}
... but that's not a Test.class
. The Test.class
, eventually, it's only the value of the key "Test"
, so the following line of code would fail anyway even if the response was correct:
Test test = mapper.readValue(responseEntity.getBody(), Test.class);
To make it simpler, I'd do this:
ObjectMapper mapper = new ObjectMapper();
JsonNode fullResponse = mapper.readTree(responseEntity.getBody());
JsonNode testNode = fullResponse.get("Test");
if ("NULL".equals(testNode.asText())) {
//you won't be able to parse the response into class Test.class.
//do what you wish to do here (throw an exception, return null etc.)
}
Test test = mapper.readValue(testNode, Test.class);
//here you should have parsed test, so do what you want with it