joelittlejohn / jsonschema2pojo

Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
http://www.jsonschema2pojo.org
Apache License 2.0
6.24k stars 1.66k forks source link

Generator doesn't respect null type when a field is required #1641

Open raphaelleu opened 3 weeks ago

raphaelleu commented 3 weeks ago

Perhaps I'm missing something, but it seems like there's no support for properly generating code/annotations, and therefore ensuring that an object matches the json schema spec for fields which are nullable but required.

Given the following schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "foo": {
      "type": [
        "string",
        "null"
      ]
    },
    "bar": {
      "type": "string"
    }
  },
  "required": [
    "foo",
    "bar"
  ]
}

both properties are generated as follows:

@JsonProperty("foo")
@Nonnull
private String foo;
/**
 * 
 * (Required)
 * 
 */
@JsonProperty("bar")
@Nonnull
private String bar;

with the following gradle task settings:

includeAdditionalProperties = false
generateBuilders = true
includeJsr305Annotations = true
includeConstructors = true
isIncludeConstructorPropertiesAnnotation = true
constructorsRequiredPropertiesOnly = true
removeOldOutput = true
useJakartaValidation = true

The problem is that my JSON spec specifies that the foo field is required while also possibly being null. However, in the generated code, it's flagged as @Nonnull. The difference between specifying a field as possibly being null type versus required is documented on the JSON schema site: "In JSON a property with value null is not equivalent to the property not being present.", as well as here: "It's important to remember that in JSON, null isn't equivalent to something being absent".