I am trying to use swagger-codegen to generate Java API client for a schema specification.
The schema uses the vendor extension x-discriminator-value
to create the inheritance model.
For example, I used the schema specification which I found as yaml here and converted to json (I wrapped the result with the "spec" root so I can send the result to the online code-generator as explained later below).
When I try to generate the Java client both locally or with the online code-generator I get that the desearilization is not done using the x-discriminator-value
value.
Instead, it is being done with the model name.
I see this in the generated JSON.java
file which contains a map from discriminator to class:
classByDiscriminatorValue.put("PhoneSetting".toUpperCase(), PhoneSetting.class);
classByDiscriminatorValue.put("SceneSetting".toUpperCase(), SceneSetting.class);
classByDiscriminatorValue.put("TextSetting".toUpperCase(), TextSetting.class);
[To see this you can post
the above json to https://generator.swagger.io/api/gen/clients/java
and check the JSON.java
file.
From what I understand, I should of gotten that the key should be the x-discriminator-value
value. So for example, since the schema has:
"SceneSetting": {
"description": "Scene Setting",
"x-discriminator-value": "SCENE",
"allOf": [
{
"$ref": "#/definitions/SectionSetting"
},
then I should have a mapping
classByDiscriminatorValue.put("SCENE".toUpperCase(), SceneSetting.class);
instead of the classByDiscriminatorValue.put("SceneSetting".toUpperCase(), SceneSetting.class);
I would appreciate any help on the matter.
I would recommend migrating to OpenAPI 3.0 – it has built-in support for discriminator mapping. There are OAS2-to-OAS3 converters to help with migration, but you'll have to update the mappings manually.
In OpenAPI 3.0, discriminator mappings are specified in the parent schema (not in child schemas). The following example is in YAML for readability, you can use https://www.json2yaml.com to convert it to JSON.
openapi: 3.0.2
components:
schemas:
# Parent schema
SectionSetting:
type: object
properties:
...
discriminator:
propertyName: PROP_NAME
mapping:
SCENE: SceneSetting
...
# Child schema
SceneSetting:
description: Scene Setting
allOf:
- $ref: '#/components/schemas/SectionSetting'
- ...
Make sure to use Swagger Codegen version 3.x because 2.x does not support OpenAPI 3.0. You can get the latest 3.x CLI JAR from Maven Central:
https://mvnrepository.com/artifact/io.swagger.codegen.v3/swagger-codegen-cli