Search code examples
javaswaggerswagger-codegen

Swagger Codegen convert "format: time" to non String


I'm trying to customize the mappings between the OpenAPI Specification string formats

  • time
  • date
  • date-time

to

  • OffsetTime
  • LocalDate
  • Instant

respectively.

I'm currently using my own custom server generator that extends JavaJerseyServerCodegen, so I made this changes and everything worked fine

@Override
public void processOpts()
{
  super.processOpts();
  typeMapping.put("DateTime", "Instant");
  typeMapping.put("date", "LocalDate");

  importMapping.put("Instant", "java.time.Instant");
  importMapping.put("LocalDate", "java.time.LocalDate");
 ...

The problem is the time format, since the codegen doens't have this format defined by default so that I can "override" it.
Is it possible to do what I want? If so how?


Solution

  • After a lot of head banging, I tried a KISS approach and got the following solution:

    @Override
    public String getSwaggerType(final Property property)
    {
      if ((property instanceof StringProperty) && ("time".equals(property.getFormat())))
      {
        return "OffsetTime";
      }
      else
      {
        return super.getSwaggerType(property);
      }
    }
    

    and now I can simply do the following

    @Override
    public void processOpts()
    {
      super.processOpts();
      typeMapping.put("DateTime", "Instant");
      typeMapping.put("date", "LocalDate");
      typeMapping.put("time", "OffsetTime");
    
      importMapping.put("Instant", "java.time.Instant");
      importMapping.put("LocalDate", "java.time.LocalDate");
      importMapping.put("OffsetTime", "java.time.OffsetTime");
      ...