Skip to content

[java][native] add generateJsonCreator to distinguish between oneOf types w/o discriminator - #25728

Open
thorstenhirsch wants to merge 7 commits into
OpenAPITools:masterfrom
thorstenhirsch:java-generate-json-creator
Open

thorstenhirsch wants to merge 7 commits into
OpenAPITools:masterfrom
thorstenhirsch:java-generate-json-creator

Conversation

@thorstenhirsch

@thorstenhirsch thorstenhirsch commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This PR fixes #25727. Besides the example in the issue I've also tested the fix successfully against a real-world openapi spec that triggered the problem.

This PR introduces a new additional property generateJsonCreator, which is false by default, because I do not dare to change the default behavior. When set to true it will add @JsonCreator constructor code for the parser to check for required properties, especially to distinguish between multiple types in an oneOf array. Actually, this might be what most people expect: a parser should fail when trying to parse a type in a oneOf array and the input does not contain the properties that are listed in the required array of said type. Unfortunately, this is not the case (at least not when unknown properties are ignored, which is the default behavior). Instead, the parser is happy with all possible types in the oneOf array and fails with this error:

Failed deserialization for Author: 2 classes match result, expected 1

So, with this PR this problem is being resolved, only 1 class will match - as long as the required fields differ between the possible oneOf types, which is probably the case in most openapi specs that don't come with a discriminator.

Please feel free not only to approve this PR, but also to change the default behavior to generateJsonCreator=true, as this is probably the expected behavior of most users.

PR checklist

  • Read the contribution guidelines.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @martin-mfg (2023/08) @KannaKim (2026/07) @AndreyVMarkelov (2026/11)


Summary by cubic

Fixes #25727 by adding an opt-in generateJsonCreator option for the Java native library so oneOf variants without a discriminator no longer deserialize into multiple classes.

Generates a @JsonCreator(mode = PROPERTIES) constructor holding required and read-only properties, so deserialization fails when a required property is missing instead of every oneOf variant matching. The option is off by default and is only implemented for the native library; other libraries get a warning and the option is disabled. Models that override an inherited property with an incompatible type fall back to the no-arg constructor.

Bug Fixes

  • Required nullable properties stay required, since the value may be null but the property must still be present to distinguish oneOf variants.
  • Uses the jacksonPackage value for XML annotation imports so Jackson 3 resolves tools.jackson.dataformat correctly.
  • Adds missing XML processing and JAXB dependencies to the native build.gradle and pom.xml templates for withXml builds.

New Features

  • Adds generateJsonCreator configuration option (native library only, Jackson 2 and 3).
  • Generates @JsonCreator constructors that chain to parent constructors for inherited required properties.

Written for commit a16e8ec. Summary will update on new commits.

View guided diff

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 44 files

Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack

View guided diff | Re-trigger cubic

@thorstenhirsch

Copy link
Copy Markdown
Contributor Author

The failing jobs are caused by 429 Too Many Requests errors (Maven Central). Could a maintainer re-run the failed jobs when convenient?

…reator

Address review feedback: a required nullable property must still be present when deserializing, otherwise it cannot distinguish oneOf variants. Also assert the generated XML/JAXB build dependencies in the XML regression test.
@thorstenhirsch
thorstenhirsch force-pushed the java-generate-json-creator branch from 338e30b to 94f01d8 Compare November 18, 2026 08:35
thorstenhirsch and others added 4 commits November 19, 2026 22:00
…libraries

Resolve the conflict with OpenAPITools#25792 (microprofile useJackson3) in the
useJackson3 option description.

generateJsonCreator is only implemented for the native library. Warn and
disable it for any other library instead of silently ignoring it, and say in
the option description that jaxrs-spec has an option with the same name.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@thorstenhirsch

Copy link
Copy Markdown
Contributor Author

@jpfinne thanks for the pointers, and I agree that the Java client options are hard to follow. I went through the templates and put together what each option does per library. It might help as a base for a cleanup discussion.

What I changed in this PR (merge with master + small fixes)

  • Resolved the conflict with [Java][microprofile] Add Jackson3 support #25792 (microprofile useJackson3) in the useJackson3 option description.
  • generateJsonCreator is now ignored with a warning for every library except native. Before, it was silently ignored.
  • I kept the name generateJsonCreator on purpose: jaxrs-spec already has an option with that name and the same purpose (there it defaults to true). The description now says so.

Why useOneOfInterfaces + useDeductionForOneOfInterfaces did not work for native

The native (and jersey2, jersey3, okhttp-gson) model.mustache ignores x-is-one-of-interface and renders oneof_model (a wrapper class). DefaultCodegen still makes the members implements <OneOf>, so they implement a class. okhttp dispatches both ways, which is the pattern to copy. I'll open a separate PR that makes native honour useOneOfInterfaces. generateJsonCreator stays useful for people who want to keep the wrapper class, as in #25727.

Option support per library (from reading the templates)

Option Works with Silently ignored / broken
useOneOfInterfaces shared-pojo libs, resttemplate/restclient/webclient, feign, microprofile, okhttp jersey2, jersey3, native, okhttp-gson: class vs interface mismatch (above)
useDeductionForOneOfInterfaces same as above, Jackson only same libraries, and whenever useOneOfInterfaces=false
useSealedOneOfInterfaces microprofile, restclient, webclient others: interface is sealed, implementors are not final
useOneOfDiscriminatorLookup jersey2, jersey3, native, okhttp-gson, okhttp description omits okhttp
generateConstructorWithAllArgs shared pojo, resttemplate/restclient/webclient, okhttp feign, jersey2/3, native, okhttp-gson, microprofile
failOnUnknownProperties libraries with a Jackson ObjectMapper resttemplate, microprofile, any Gson setup
openApiNullable Jackson-based libraries forced to false for microprofile and okhttp, without a warning
generateJsonCreator native + Jackson everything else (now warns)

@JsonCreator for read-only properties is generated in 7 different ways across the pojo templates (annotation, required=, withXml guard all differ).

Recommendations

  1. One place for "option X is supported by libraries Y". JSPECIFY_SUPPORTED_LIBRARIES already does this for one option. A Map<option, Set<library>> could build the description text and also warn (or fail) in processOpts, instead of the current free-text "Only supported for..." sentences and ad-hoc checks. A supportedLibraries field on CliOption would let the docs generator render the matrix.
  2. Warn instead of ignoring, using the same warn-and-disable pattern for the combinations marked above (starting with useOneOfInterfaces on jersey/okhttp-gson until they support it).
  3. Fewer copies of the model templates. There are about 5 families, the 4 oneof_model implementations are independent copies, and each pojo.mustache is a full copy. Shared partials (e.g. for the creator constructor) would let a feature be added once. jersey2/jersey3 are only ~2 lines apart, so that would be a cheap start.
  4. generateJsonCreator long-term: move it to AbstractJavaCodegen so the other pojo families can use it, and consider making true the default in the next major version (as jaxrs-spec does).

Happy to split any of these into separate issues/PRs if you think they are worth pursuing.

@thorstenhirsch

Copy link
Copy Markdown
Contributor Author

Too Many Requests (429) ☹️

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][JAVA][native] oneOf without discriminator rejects valid payloads when variant required properties differ

1 participant