Reputation: 1474
I am consuming an API that is outside of my control with a Swagger contract using the Swagger codegen CLI Jar version 2.3.1 and using the java8
date library option, language is also Java.
In the API there are a few datetime fields all defined as :
"type": "string",
"format": "date-time"
Most of the values include the timezone, however one in particular does not. So we get both of these formats in fields that are defined in the same way:
"1963-08-15T23:59:59+02:00"
"1963-08-15T23:59:59"
This causes problems with the deserialzer as it never knows what format to handle.
I am using OffsetDateTime
in the generated DTO classes as LocalDateTime
just doesn't work - the generated code doesn't include a Gson adapter for it (See https://github.com/swagger-api/swagger-codegen/issues/6992).
I have tried setting a formatter for the deserializer with different formats, but it doesn't work, mostly because the second format above excludes the zone information:
ApiClient apiClient = new ApiClient();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[xxx]");
apiClient.setOffsetDateTimeFormat(dtf);
I'm hoping to not edit the generated code too much as I would like to be able to regenerate in the future and I can't change the values being returned by the API as it's external.
Is there a way to tell the generated client to deserialize the different formats into OffsetDateTime
, or perhaps default the time zone to something specific?
Upvotes: 3
Views: 10015
Reputation: 1474
I've worked around this problem by editing the generated JSON.java
file and changing the OffsetDateTimeTypeAdapter
class to use a ZonedDateTime
in the conversion in the read
methofd:
return ZonedDateTime.parse(date, formatter).toOffsetDateTime();
Then I've added the JSON.java
file to the .swagger-codegen-ignore
file. I doubt that file will change often.
Upvotes: 1