OpenApi java.time.Duration default format

296 views Asked by At

I am using springdoc to generate my OpenAPI documentation.

public class MyDto {
    ....
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private Duration duration;
    ....
}

OpenApi shows the definition of MyDto as below, the duration gets deserialized to something similar to:

"duration": {
    "seconds": 0,
    "nano": 0,
    "negative": true,
    "zero": true,
    "units": [
      {
        "dateBased": true,
        "timeBased": true,
        "duration": {
          "seconds": 0,
          "nano": 0,
          "negative": true,
          "zero": true
        },
        "durationEstimated": true
      }
    ]
  }

I want it to be formated as a String without having to add @Schema(type = "string", format = "duration") to each java.util.Duration in all of my DTOs on each Duration field.

I have jackson-datatype-jsr310 on my classpath and serializing/deserializing payloads works as expected using ISO 8601 formatted Strings, except for OpenAPI showing wrong format.

Is it possible to somehow tell OpenAPI to treat java.util.Duration as a String by default?

1

There are 1 answers

0
alturkovic On BEST ANSWER

I managed to solve this myself. Here is a configuration example if someone else has the same problem:

@Configuration
class SpringDocConfiguration implements InitializingBean
{
    @Override
    public void afterPropertiesSet()
    {
        SpringDocUtils.getConfig().replaceWithSchema(Duration.class, new StringSchema().example("PT10S"));
    }
}