victools / jsonschema-generator

Java JSON Schema Generator – creating JSON Schema (Draft 6, Draft 7, Draft 2019-09, or Draft 2020-12) from Java classes
https://victools.github.io/jsonschema-generator
Apache License 2.0
391 stars 57 forks source link

Swagger 2's default and allowableValues do not consider the property's type #455

Open Nephery opened 2 months ago

Nephery commented 2 months ago

For the following Swagger 2 module properties:

From @Schema(allowableValues = …) on fields/methods, derive its "const"/"enum". From @Schema(defaultValue = …) on fields/methods, derive its "default".

The outputted JSON always treats them as Strings, and does not consider the actual type of the property.

For example, if I have the following:

public class TestSchema {
    @Schema(allowableValues = "true")
    public boolean myRestrictedBoolean;
}

This would produce a schema like:

{
  "type" : "object",
  "properties" : {
    "myRestrictedBoolean" : {
      "type" : "boolean",
      "const" : "true"
    }
  }
}

Instead of "const" : "true", I would have expected this to be "const" : true (i.e. not a String value). The same happens for any other primitive types.

CarstenWickner commented 2 months ago

Hi @Nephery,

Yeah, that's the downside of the Swagger annotation providing everything as String values. We could add extra smarts to cover some straightforward scenarios such as this one, but to be honest, I'd expect something like the jakarta @AssertTrue validation annotation to be present in this case, which allows enforcement and can be picked up without having to parse a String.

I'm open to a PR though, if you deem it worthwhile. I fully agree, that the schema currently being generated there is invalid. The issue can be avoided by not using the @Schema(allowableValues = "true") in such a case and/or a fix is required here.

Nephery commented 2 months ago

That's fair.

I raised #456 to add support for Jakarta @AssertTrue and @AssertFalse.

Maybe I'll come back around in the future to try and raise a PR to add some support for primitive types in @Schema(allowableValues = "true"). But adding support for Jakarta @AssertTrue and @AssertFalse does actually solve my immediate issue. So that's good enough for me for now. 🙂

CarstenWickner commented 2 months ago

The support for the Jakarta @AssertTrue/@AssertFalse annotations has been released in v4.36.0.

I'm leaving this issue open for now, as the original topic (Swagger annotations) has not yet been resolved.