Skip to content

[BUG] [JAVA] validateJsonElement fails for required nullable fields#22912

Merged
wing328 merged 10 commits intoOpenAPITools:masterfrom
marceljk:fix_issue_18516
Feb 7, 2026
Merged

[BUG] [JAVA] validateJsonElement fails for required nullable fields#22912
wing328 merged 10 commits intoOpenAPITools:masterfrom
marceljk:fix_issue_18516

Conversation

@marceljk
Copy link
Contributor

@marceljk marceljk commented Feb 6, 2026

This PR supersedes #18518.

fixes the issues with required nullable fields #18516

Credits to @fanqiewanzi for the original pull request

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • 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.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • 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 @sreeshas @jfiala @lukoyanov @cbornet @jeff9finger @karismann @Zomzog @lwlee2608 @martin-mfg


Summary by cubic

Fixes #18516 by updating the Java okhttp-gson generator to accept null for fields that are both required and nullable, preventing false validation errors in validateJsonElement.

  • Bug Fixes
    • In pojo.mustache, treat required arrays and object references as valid when the JSON value is explicitly null (added isJsonNull checks).
    • Skip nested model/enum validation when a required nullable field is JsonNull.
    • Added tests and fixtures (issue_18516.yaml, JavaClientCodegenTest) to verify generated code includes the new null checks.
    • Extended Petstore samples and docs with a /fake/required-nullable-body endpoint and models (RequiredNullableBody, NullableEnum) to cover required+nullable cases.

Written for commit 87d9898. Summary will update on new commits.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

3 issues found across 18 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache:389">
P2: Required nullable model arrays can still throw on JSON null: the new condition allows JsonNull to pass, but getAsJsonArray is still called unconditionally, which throws IllegalStateException on JsonNull.</violation>
</file>

<file name="samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/RequiredNullableBody.java">

<violation number="1" location="samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/RequiredNullableBody.java:172">
P2: Enum validation does not reject unknown values; invalid `custom_enum` strings pass validation and deserialize to null, defeating required enum validation.</violation>
</file>

<file name="samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableEnum.java">

<violation number="1" location="samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableEnum.java:73">
P2: validateJsonElement ignores the NullableEnum.fromValue result; invalid enum strings return null and are accepted without error, so enum validation is ineffective for this type.</violation>
</file>

Since this is your first cubic review, here's how it works:

  • cubic automatically reviews your code and comments on bugs and improvements
  • Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
  • Ask questions if you need clarification on any suggestion

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.


public static void validateJsonElement(JsonElement jsonElement) throws IOException {
String value = jsonElement.getAsString();
CustomEnumEnum.fromValue(value);
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Feb 6, 2026

Choose a reason for hiding this comment

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

P2: Enum validation does not reject unknown values; invalid custom_enum strings pass validation and deserialize to null, defeating required enum validation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/RequiredNullableBody.java, line 172:

<comment>Enum validation does not reject unknown values; invalid `custom_enum` strings pass validation and deserialize to null, defeating required enum validation.</comment>

<file context>
@@ -0,0 +1,766 @@
+
+    public static void validateJsonElement(JsonElement jsonElement) throws IOException {
+      String value = jsonElement.getAsString();
+      CustomEnumEnum.fromValue(value);
+    }
+  }
</file context>
Fix with Cubic

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The validation of enums and the related template modelInnerEnum.mustache were not changed in this PR. So this was already an issue before this PR and this PR doesn't aim to fix the validation of enums

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@cubic-dev-ai can this comment be considered as solved?

Copy link
Contributor

Choose a reason for hiding this comment

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

@marceljk Looking at the conversation history and the code, I can see that you've correctly identified that enum validation was not changed in this PR and was a pre-existing issue.

The comment I raised was about the validateJsonElement method for CustomEnumEnum (line 172), which calls fromValue() but doesn't throw an exception when an invalid enum value is encountered—it just returns null. This means invalid enum strings pass validation silently.

However, since:

  1. This enum validation behavior existed before your PR
  2. Your PR specifically targets the nullable + required field validation issue ([BUG] [JAVA] validateJsonElement failed when a field is decorated with both nullable and required #18516)
  3. You've explicitly stated this PR doesn't aim to fix enum validation
  4. The template modelInnerEnum.mustache wasn't modified in this PR

Yes, this comment can be considered resolved/not applicable to this PR's scope. The enum validation issue is a separate concern that should be tracked and fixed independently if desired. Your PR successfully addresses the original bug about required nullable fields failing validation, which is what matters here.

If you want to track the enum validation issue separately, it would need changes to the modelInnerEnum.mustache template to make validateJsonElement throw an exception when fromValue() returns null for invalid values.


public static void validateJsonElement(JsonElement jsonElement) throws IOException {
String value = jsonElement.getAsString();
NullableEnum.fromValue(value);
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Feb 6, 2026

Choose a reason for hiding this comment

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

P2: validateJsonElement ignores the NullableEnum.fromValue result; invalid enum strings return null and are accepted without error, so enum validation is ineffective for this type.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableEnum.java, line 73:

<comment>validateJsonElement ignores the NullableEnum.fromValue result; invalid enum strings return null and are accepted without error, so enum validation is ineffective for this type.</comment>

<file context>
@@ -0,0 +1,76 @@
+
+  public static void validateJsonElement(JsonElement jsonElement) throws IOException {
+    String value = jsonElement.getAsString();
+    NullableEnum.fromValue(value);
+  }
+}
</file context>
Fix with Cubic

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The validation of enums and the related template modelInnerEnum.mustache were not changed in this PR. So this was already an issue before this PR and this PR doesn't aim to fix the validation of enums

@wing328
Copy link
Member

wing328 commented Feb 6, 2026

@marceljk thanks for creating this PR

can you please have a look at the feedback/review by cubic-dev-ai? (not that we must address these in this PR...)

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 3 files (changes from recent commits).

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache">

<violation number="1" location="modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache:388">
P2: Required non-nullable arrays of models can now be set to JSON null without error because validation is skipped for JsonNull, allowing invalid payloads to pass.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@marceljk
Copy link
Contributor Author

marceljk commented Feb 6, 2026

@wing328 I had a look to the feedback of cubic-dev-ai and solved or replied to the comments.

@wing328
Copy link
Member

wing328 commented Feb 6, 2026

can you please review the build failure?

2026-02-06T14:43:09.2595692Z [ERROR] Failures: 
2026-02-06T14:43:09.2597506Z [ERROR] org.openapitools.codegen.java.JavaClientCodegenTest.testRequiredAndNullableAreBothTrue
2026-02-06T14:43:09.2604867Z [ERROR]   Run 1: JavaClientCodegenTest.testRequiredAndNullableAreBothTrue:3791 File '/tmp/test18366895161306578505/src/main/java/org/openapitools/client/model/SomeObject.java' does not contain line [if (!jsonObj.get("users").isJsonArray() && !jsonObj.get("users").isJsonNull()) {] expected [true] but found [false]
2026-02-06T14:43:09.2609747Z [ERROR]   Run 2: JavaClientCodegenTest.testRequiredAndNullableAreBothTrue:3791 File '/tmp/test5248775445590077605/src/main/java/org/openapitools/client/model/SomeObject.java' does not contain line [if (!jsonObj.get("users").isJsonArray() && !jsonObj.get("users").isJsonNull()) {] expected [true] but found [false]
2026-02-06T14:43:09.2613885Z [ERROR]   Run 3: JavaClientCodegenTest.testRequiredAndNullableAreBothTrue:3791 File '/tmp/test12576583108002073056/src/main/java/org/openapitools/client/model/SomeObject.java' does not contain line [if (!jsonObj.get("users").isJsonArray() && !jsonObj.get("users").isJsonNull()) {] expected [true] but found [false]
2026-02-06T14:43:09.2616527Z [ERROR] Tests run: 3647, Failures: 1, Errors: 0, Skipped: 4
2026-02-06T14:43:09.3629075Z [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.2.5:test (default-test) on project openapi-generator: There are test failures.
2026-02-06T14:43:09.3633495Z [ERROR] 
2026-02-06T14:43:09.3634736Z [ERROR] Please refer to /home/runner/work/openapi-generator/openapi-generator/modules/openapi-generator/target/surefire-reports for the individual test results.

@marceljk
Copy link
Contributor Author

marceljk commented Feb 6, 2026

solved the failing builds

@wing328
Copy link
Member

wing328 commented Feb 7, 2026

thanks for your contribution.

let's give it a try

@wing328 wing328 merged commit 54fe232 into OpenAPITools:master Feb 7, 2026
91 checks passed
@wing328 wing328 added this to the 7.20.0 milestone Feb 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] [JAVA] validateJsonElement failed when a field is decorated with both nullable and required

3 participants