openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

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

Open fanqiewanzi opened this issue 1 year ago • 1 comments

Bug Report Checklist

  • [x] Have you provided a full/minimal spec to reproduce the issue?
  • [x] Have you validated the input using an OpenAPI validator (example)?
  • [x] Have you tested with the latest master to confirm the issue still exists?
  • [x] Have you searched for related issues/PRs?
  • [x] What's the actual output vs expected output?
  • [ ] [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
openapi-generator version

(7.5.0)the latest master branch

OpenAPI declaration file content or url
Generation Details

run command to generate: openapi-generator-cli generate -i test.yaml -g java -o test

Steps to reproduce

after generating the code, you will find out nullable didn't work, there is no nullable judgement in validateJsonElement function. I'm not quiet sure whether this is a bug or something. But according to the OpenAPI YAML specification and the judgment of required in the code of this repository, I prefer this to be a bug.

this is the validateJsonElement function of SomeObject:

image

Except for the yaml example I gave, all other errors involving required and nullable occur at the same time.

Related issues/PRs

Not found yet.

Suggest a fix

before:

{{#required}}
      // ensure the required json array is present
      if (jsonObj.get("{{{baseName}}}") == null) {
        throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`");
      } else if (!jsonObj.get("{{{baseName}}}").isJsonArray()) {
        throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString()));
      }
      {{/required}}

after:

{{#required}}
      // ensure the required json array is present
      if (jsonObj.get("{{{baseName}}}") == null) {
        throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`");
      } else if (!jsonObj.get("{{{baseName}}}").isJsonArray() {{#isNullable}} && !jsonObj.get("{{baseName}}").isJsonNull(){{/isNullable}}) {
        throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString()));
      }
      {{/required}}

Other types of processing are also similar。

fanqiewanzi avatar Apr 27 '24 06:04 fanqiewanzi

can you please file a PR with the suggested fix when you've time?

wing328 avatar Apr 27 '24 09:04 wing328