Reputation: 206
I have a swagger.json specification that I can not change. I'm using swagger-codegen to create a library from my swagger.json like this:
$ java -jar swagger-codegen-cli.jar generate -i swagger.json -l java -o .
The problem is that in my swagger.json, a few formats are declared as date-time
and codegen converts those to OffsetDateTime
class types... but the response from my service requests come on the form of LocalDateTime, like this
{....,
"expirationDeadline": "2022-04-22T10:36:13.383",
....}
So, when I'm using the library and I try to deserialize the JSONObject that contains2022-04-22T10:36:13.383
to my Class, it fails because it can't convert 2022-04-22T10:36:13.383
to an OffsetDateTime
.
Eventually after some search I followed some other threads like this one, and I managed to change the OffsetDateTime
types to LocalDateTime
using import and type mappings like so:
$ java -jar swagger-codegen-cli.jar generate \
-i updated-swagger.json \
-l java \
-o ./java-client-swagger-codegen/ \
--import-mappings org.threeten.bp.OffsetDateTime=org.threeten.bp.LocalDate \
--type-mappings OffsetDateTime=LocalDate
But now the problem is that swagger-codegen
only creates JSON class with OffsetDateTimeTypeAdaper
, DateTypeAdapter
, LocalDateTypeAdapter
and SqlDateTypeAdapter
like this:
So now whenever I try to deserialize the object that contains my date in the LocalDateTime format, I end up getting this error:
serialize json java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 at $.expirationDeadline
date-time
formats to OffsetDateTime
and then manually changed "expirationDeadline": "2022-04-22T10:36:13.383"
to "expirationDeadline": "2022-04-22T10:36:13.383+01:00"
and it works fine.date-time
formats to LocalDate
and then manually ganged "expirationDeadline": "2022-04-22T10:36:13.383"
to "expirationDeadline": "2022-04-22"
and it works fine.LocalDateTimeTypeAdapter
just copying the logic from the other adapter, and now It works, I can convert the expected format to LocalDateTime
format!Unfortunatly I can not change this format, so I assume I need a way for my swagger codegen
to generate this LocalDateTimeTypeAdapter
when I run the command. Is there any argument I can give to my command for this to happen? Can anyone help me?
Upvotes: 5
Views: 3963
Reputation: 11
Don't know if you found a solution or another workaround to the problem, but what worked for me was using another library when generating the client so the parsing of JSON would be done using Jackson not GSON.
https://github.com/swagger-api/swagger-codegen#customizing-the-generator
In the client generation script you should for example add the following parameter to use the feign library:
--library feign
And just in case anyone who runs into the same problem using the OpenAPI generator stubmles here, the solution is essentially the same - you should use some other library to use the Jackson parser: https://openapi-generator.tech/docs/generators/java/
Upvotes: 1