João Quintanilha
João Quintanilha

Reputation: 206

Convert swagger format: date-time to LocalDateTime.class

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:

enter image description here

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

What I tried so far:

Concluding (The actual call for help)

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

Answers (1)

Silver
Silver

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

Related Questions