skip to Main Content

I am working with an external API and have generated the Java client classes using the OpenAPI generator. One of the fields defined in the response is marked as being of a date type as shown below and the equivalent Java code is a method with a type of LocalDate. So far so good.

"maturity": {
  "type": "string",
  "description": "Maturity date",
  "nullable": true,
  "format": "date"
}

Unfortunately, their API seems to use the string value of "Unspecified" to indicate null in some of their responses.

  "name": "abc",
  "start": null,
  "maturity": "Unspecified",

This produces the following exception in Jackson during the JSON deserialization process (which is expected):

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String "Unspecified": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text 'Unspecified' could not be parsed at index 0

While I have raised this with them, it may take them some to fix.

My more general question is whether there is an easy way within Jackson to treat malformed types such as a specific string value of "Unspecified" as being null? One option is for me to pre-process the response before handing it over for JSON deserialization but I was wondering if there are any other better ideas?

2

Answers


  1. Chosen as BEST ANSWER

    In the end I went for the approach of using Jackson's DeserializationProblemHandler as I wanted to make this applicable more globally. It can be adapted to handle different types and invalid values as required.

    var objectMapper = new ObjectMapper().addHandler(new DeserializationProblemHandler() {
    
      final String UNSPECIFIED = "Unspecified";
    
      @Override
      public Object handleWeirdStringValue(DeserializationContext ctxt,
                                           Class<?> targetType,
                                           String valueToConvert,
                                           String failureMsg) throws IOException 
      {
        return UNSPECIFIED.equals(valueToConvert) && targetType.equals(LocalDate.class) ? 
          null : super.handleWeirdStringValue(ctxt, targetType, valueToConvert, failureMsg);
      }
    });
    

  2. You should look at @JsonDeserialize annotation and provide your custom deserializer to handle such cases. This way you can mark "Unspecified" as null and parse the actual date as LocalDate.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search