Skip to content

Applying schema defaults does not compute $ref #868

@ilPittiz

Description

@ilPittiz

More of a feature request than an issue: I followed the JSON Schema Walkers guide about applying defaults, and expected default values to be also computed when the related schema node is a reference, instead of 'inline' schema nodes as per PropertiesValidator#getDefaultNode(Map.Entry<String, JsonSchema>)

Example:

schema.json

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "",
  "type": "object",
  "properties": {
    "s": {
      "type": "string",
      "default": "S"
    },
    "ref": { "$ref": "#/$defs/r" }
  },
  "required": [ "s", "ref" ],

  "$defs": {
    "r": {
      "type": "string",
      "default": "REF"
    }
  }
}

Code:

JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
SchemaValidatorsConfig schemaValidatorsConfig = new SchemaValidatorsConfig();
schemaValidatorsConfig.setApplyDefaultsStrategy(new ApplyDefaultsStrategy(true, true, true));
schemaValidatorsConfig.setLoadCollectors(true)
JsonSchema jsonSchema = schemaFactory.getSchema(getClass().getClassLoader().getResourceAsStream("schema.json"), schemaValidatorsConfig);

JsonNode inputNode = objectMapper.readTree('{}');
ValidationResult result = jsonSchema.walk(inputNode, true);

System.out.println(inputNode.toString());
System.out.println(result.getValidationMessages());

Output:

{"s":"S"}
[$.ref: is missing but it is required]

Having instead as output

{"s":"S","ref":"REF"}
[]

would be a total game-changer for me: the project I'm working on has a huge amount of shared 'components', referenced across all local JSON schemas validating user input, and adding the default values across these local JSON schemas is simply not doable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions