Open drmoeller opened 2 years ago
@drmoeller,
I faced the same problem. Thank you for your fix!
To get rid of manual replacements I automated this work with special task ApiModelPostProcessor in build.gradle.kts
.
May be someone will find it usefull.
Description
Currently I'm using OpenAPI generator only to generate Kotlin model types representing exchanged HTTP body entities.
As far as I can tell deserialization of JSON entities from HTTP request bodies works as expected; but I've recognized deviation when serializing received object graphs back to JSON in response bodies: Duplication of JSON-field used as polymorphism discriminator.
openapi-generator version
5.3.1
(currently resolved from wildcard declaration5.+
withinbuild.gradle
file)OpenAPI declaration file content or url
I've simplified OpenAPI specification
test-specification.yml
for easier testing:OpenAPI specification declares schemata of central entity
Order
having two fields, one of them polymorphic with two possible sub-types ofProduct
:ProductOne
andProductTwo
. Fieldtype
is used as discriminator.Generation Details
Corresponding chapter from Gradle build file
build.gradle
looks like so:As you can see,
jackson
is configured asserializationLibrary
, cause I'm already using this lib for other JSON-related purposes within the project.Steps to reproduce
Related issues/PRs
Unknown
Suggest a fix
Here is generated Kotlin code of one of the types involved (removed comments,
@file:Suppress
annotation, etc.):Provided Spock-driven test case uses following pretty-printed JSON to get deserialized to the generated data types (using Jackson framework):
Test case shows proper deserialization to the expected graph of instances, all fields contain the expected content!
But, when serializing the received object graph back to JSON, I got the following result:
As you can see, discriminator field
type
appears twice!Playing around with some options, I found a solution to remove this duplicate line by modifying generated code by hand. Within classes
ProductOne
andProductTwo
, addaccess = JsonProperty.Access.WRITE_ONLY
instruction withJsonProperty
annotation ontype
field like so:I've not deeply tested this modification for side effects, but it reproducibly solves the problem at hand: Deserialising JSON to an object graph and serializing it back to JSON yields exactly the same pretty-printed JSON document (pretty-printed to remove issues with line breaks, etc.).
So I suggest to modify code generator to generate shown slightly changed annotation to solve this issue.