jsonschema-generator
jsonschema-generator copied to clipboard
Provide "examples" field in generated JSON schema
Examples give a better context for error messages and other tooling based on the generated schema.
Would it be possible to parse provided example
fields from annotations into a JSON schema examples
list?
Example for Swagger
@Schema(description = "The locale for the event.", required = true, implementation = String.class, example = "en_US")
should result in the following schema
{
"locale": {
"type": "string",
"description": "The locale for the event.",
"examples": [
"en_US"
]
}
}
Hi @nerdgore,
Sure, that is possible.
You can adapt the getSchemaAnnotationValue()
method from the Swagger2Module
:
https://github.com/victools/jsonschema-generator/blob/0f1c95bcb2d761e3de7a6bbf7a8cfef3f67d70b4/jsonschema-module-swagger-2/src/main/java/com/github/victools/jsonschema/module/swagger2/Swagger2Module.java#L469-L486
Your specific configuration would look like this then:
builder.forFields()
.withInstanceAttributeOverride((collectedMemberAttributes, member, context) ->
this.getSchemaAnnotationValue(member, annotation -> annotation.example(), val -> !val.isEmpty())
.map(exampleString -> Stream.of(exampleString.split(",")).map(String::trim).filter(val -> !val.isEmpty()).collect(Collectors.toList()))
.filter(examples -> !examples.isEmpty())
.ifPresent(examples -> examples.forEach(collectedMemberAttributes.withArray("examples")::add)));
The "examples" keyword is currently not part of the standard feature set. As one might want to consider the specific data type for which examples are being provided. So far, I didn't bother coming up with a proper implementation. But the above should work for textual examples.