### Complete Schema Generation Example Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md A minimal example demonstrating how to generate a JSON schema from a Java class. Ensure you have the necessary imports. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import tools.jackson.databind.JsonNode; ``` ```java SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toString()); ``` -------------------------------- ### Complete Example with Swagger2Module Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-swagger-2/README.md Demonstrates a complete example of generating a JSON schema with Swagger 2 annotations using the jsonschema-generator library. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.swagger2.Swagger2Module; import tools.jackson.databind.JsonNode; ``` ```java Swagger2Module module = new Swagger2Module(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON) .with(module); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toString()); ``` -------------------------------- ### Complete Example: Generate Schema with Swagger Module Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-swagger-1.5/README.md A full example demonstrating how to configure the SchemaGenerator with the SwaggerModule and generate a JSON Schema from a Java class. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.swagger15.SwaggerModule; import tools.jackson.databind.JsonNode; ``` ```java SwaggerModule module = new SwaggerModule(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON) .with(module); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toString()); ``` -------------------------------- ### Complete Example with JakartaValidationOption Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-jakarta-validation/README.md A full example demonstrating how to configure the SchemaGenerator with the JakartaValidationModule, including a specific option to include pattern expressions. It then generates and prints the JSON schema for a given class. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.jakarta.validation.JakartaValidationModule; import com.github.victools.jsonschema.module.jakarta.validation.JakartaValidationOption; import tools.jackson.databind.JsonNode; ``` ```java JakartaValidationModule module = new JakartaValidationModule(JakartaValidationOption.INCLUDE_PATTERN_EXPRESSIONS); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON) .with(module); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toString()); ``` -------------------------------- ### Complete Example with JavaxValidationModule and Options Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-javax-validation/README.md A full example demonstrating how to configure the SchemaGenerator with JavaxValidationModule, including specific options like including pattern expressions. This generates a JSON schema for a given Java class. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationOption; import tools.jackson.databind.JsonNode; ``` ```java JavaxValidationModule module = new JavaxValidationModule(JavaxValidationOption.INCLUDE_PATTERN_EXPRESSIONS); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON) .with(module); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toString()); ``` -------------------------------- ### Start Slate Docker Container Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/README.md Run a Docker container to serve the Slate documentation. This command maps the host's port 4567 to the container's port 4567 and mounts local build and source directories into the container. ```sh docker run -d --rm --name slate -p 4567:4567 -v $(pwd)/build:/srv/slate/build -v $(pwd)/source:/srv/slate/source slate ``` -------------------------------- ### Configure Modules Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Specify modules to be used during schema generation with the `` element. This example enables the Jackson module. ```xml com.myOrg.myApp.MyClass Jackson ``` -------------------------------- ### Minimal JSON Schema Generation Example Source: https://github.com/victools/jsonschema-generator/blob/main/README.md This example demonstrates the basic setup for generating a JSON Schema from a Java class using the SchemaGenerator. It utilizes a plain JSON option preset and the Draft 2020-12 schema version. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import tools.jackson.databind.JsonNode; ``` ```java SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toPrettyString()); ``` -------------------------------- ### Define Custom Option Preset Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md Create a custom configuration by starting with an empty OptionPreset and adding desired options. This allows for fine-grained control over schema generation. ```java import com.github.victools.jsonschema.generator.Option; import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, new OptionPreset()) .with(Option.ADDITIONAL_FIXED_TYPES, Option.PUBLIC_NONSTATIC_FIELDS); ``` -------------------------------- ### Example Schema with Target Type Overrides Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-advanced.md This JSON demonstrates how the 'anyOf' keyword is used to represent multiple possible types for a schema property, as configured by target type overrides. ```json { "type": "object", "properties": { "value": { "anyOf": [ { "type": "string" }, { "type": "number" } ] } } } ``` -------------------------------- ### Initialize Jackson Module with Options Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_jackson-module.md Instantiate the JacksonSchemaModule with desired JacksonOptions and use it to configure the SchemaGeneratorConfigBuilder. This example shows how to flatten enums from @JsonValue. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.jackson.JacksonOption; import com.github.victools.jsonschema.module.jackson.JacksonSchemaModule; JacksonSchemaModule module = new JacksonSchemaModule( JacksonOption.FLATTENED_ENUMS_FROM_JSONVALUE ); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Configure Field Title and Description Resolvers Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Customize the 'title' and 'description' attributes for fields during schema generation. This example shows how to include the field name, its scope (fake or real), and its type description. ```java SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09); configBuilder.forField() .withTitleResolver(field -> field.getName() + " = " + (field.isFakeContainerItemScope() ? "(fake) " : "(real) ") + field.getSimpleTypeDescription()) .withDescriptionResolver(field -> "original type = " + field.getContext().getSimpleTypeDescription(field.getDeclaredType())); JsonNode mySchema = new SchemaGenerator(configBuilder.build()) .generateSchema(MyClass.class); ``` ```java class MyClass { public List texts; } ``` ```json { "type": "object", "properties": { "texts": { "type": "array", "title": "texts = (real) List", "description": "original type = List", "items": { "type": "string", "title": "texts = (fake) String", "description": "original type = List" } } } } ``` -------------------------------- ### Configure Number Inclusive Minimum Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withNumberInclusiveMinimumResolver` to set inclusive minimum values for number types, fields, or methods. This example resolves minimums for `PositiveInt`, fields with `@NonNegative`, and methods with `@Minimum`. ```java configBuilder.forTypesInGeneral() .withNumberInclusiveMinimumResolver(scope -> scope.getType().getErasedType() == PositiveInt.class ? BigDecimal.ONE : null); configBuilder.forFields() .withNumberInclusiveMinimumResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(NonNegative.class) == null ? null : BigDecimal.ZERO); configBuilder.forMethods() .withNumberInclusiveMinimumResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Minimum.class)) .filter(a -> !a.exclusive()).map(Minimum::value).orElse(null)); ``` -------------------------------- ### Configure Number Inclusive Maximum Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withNumberInclusiveMaximumResolver` to set inclusive maximum values for number types, fields, or methods. This example sets maximums for `int.class`, fields with `@NonPositive`, and methods with `@Maximum`. ```java configBuilder.forTypesInGeneral() .withNumberInclusiveMaximumResolver(scope -> scope.getType().getErasedType() == int.class ? new BigDecimal(Integer.MAX_VALUE) : null); configBuilder.forFields() .withNumberInclusiveMaximumResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(NonPositive.class) == null ? null : BigDecimal.ZERO); configBuilder.forMethods() .withNumberInclusiveMaximumResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Maximum.class)) .filter(a -> !a.exclusive()).map(Maximum::value).orElse(null)); ``` -------------------------------- ### Configure String Pattern Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withStringPatternResolver` to define custom regex patterns for string types, fields, or methods. This example shows how to resolve patterns for UUIDs, email fields, and fields annotated with `@Pattern`. ```java configBuilder.forTypesInGeneral() .withStringPatternResolver(scope -> scope.getType().getErasedType() == UUID.class ? "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" : null); configBuilder.forFields() .withStringPatternResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(Email.class) == null ? null : "^.+@.+\\..+$"); configBuilder.forMethods() .withStringPatternResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Pattern.class)) .map(Pattern::value).orElse(null)); ``` -------------------------------- ### Using Glob Patterns for Class and Package Selection Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Demonstrates the use of glob patterns with slashes for selecting classes and packages, allowing for more flexible filtering based on naming conventions. ```xml com/myOrg/myApp/My* com/myOrg/myApp/package? com/myOrg/myApp/**Hidden* ``` -------------------------------- ### Initialize Swagger 1.5 Module Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_swagger-15-module.md Demonstrates how to initialize the SwaggerModule with specific options and configure the SchemaGeneratorConfigBuilder. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.swagger15.SwaggerModule; import com.github.victools.jsonschema.module.swagger15.SwaggerOption; SwaggerModule module = new SwaggerModule( SwaggerOption.ENABLE_PROPERTY_NAME_OVERRIDES, SwaggerOption.IGNORING_HIDDEN_PROPERTIES ); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Navigate to slate-docs Directory Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/README.md Change the current directory to the slate-docs folder. This is the first step before building the documentation. ```sh cd ./slate-docs ``` -------------------------------- ### Include Standard Modules with Options Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_maven-plugin.md Incorporate standard modules, such as Jackson, and configure their options using the `` tag. ```xml Jackson ``` -------------------------------- ### Ignore Fields and Methods Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Define checks to ignore specific fields or methods during schema generation. Fields starting with an underscore or methods that are not void and return `Object.class` can be excluded. ```java configBuilder.forFields() .withIgnoreCheck(field -> field.getName().startsWith("_")); configBuilder.forMethods() .withIgnoreCheck(method -> !method.isVoid() && method.getType().getErasedType() == Object.class); ``` -------------------------------- ### Configure Schema Generation with OptionPresets Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md Demonstrates how to configure the schema generator using predefined OptionPresets like PLAIN_JSON. This preset is suitable for representing JSON data structures. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; ``` ```java SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON); ``` -------------------------------- ### Build Slate Docs via Docker Container Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/README.md Execute the Middleman build command inside the running Docker container to generate the documentation. This command is run interactively. ```sh docker exec -it slate /bin/bash -c "bundle exec middleman build" ``` -------------------------------- ### Dynamically Set additionalProperties Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md Configure the 'additionalProperties' attribute in JSON Schema. This example shows how to forbid additional properties by default and then allow them for Map types, resolving to the Value type. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import java.util.Map; SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(Option.FORBIDDEN_ADDITIONAL_PROPERTIES_BY_DEFAULT); configBuilder.forTypesInGeneral() .withAdditionalPropertiesResolver((scope) -> { if (scope.getType().isInstanceOf(Map.class)) { // within a Map allow additionalProperties of the Value type // if no type parameters are defined, this will result in additionalProperties to be omitted (by way of return Object.class) return scope.getTypeParameterFor(Map.class, 1); } return null; }); ``` -------------------------------- ### Configure Number Exclusive Maximum Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withNumberExclusiveMaximumResolver` to define exclusive maximum values for number types, fields, or methods. This example handles `NegativeInt`, fields with `@Negative`, and methods with `@Maximum` (exclusive). ```java configBuilder.forTypesInGeneral() .withNumberExclusiveMaximumResolver(scope -> scope.getType().getErasedType() == NegativeInt.class ? BigDecimal.ZERO : null); configBuilder.forFields() .withNumberExclusiveMaximumResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(Negative.class) == null ? null : BigDecimal.ZERO); configBuilder.forMethods() .withNumberExclusiveMaximumResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Maximum.class)) .filter(Maximum::exclusive).map(Maximum::value).orElse(null)); ``` -------------------------------- ### Define Use of Custom Modules Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Enable a custom module by providing its fully qualified class name in ``. Ensure the custom module is on the classpath and has a default constructor. Options cannot be configured for custom modules. ```xml com.myOrg.myApp.MyClass com.myOrg.myApp.CustomModule ``` -------------------------------- ### Selecting Classes and Packages for Generation Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Configures the plugin to generate schemas for specific classes and all classes within specified packages. It also shows how to exclude certain classes from the generation process. ```xml com.myOrg.myApp.MyClass com.myOrg.myApp.package1 com.myOrg.myApp.package2 com.myOrg.myApp.package2.HiddenClass ``` -------------------------------- ### Configure Number Exclusive Minimum Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withNumberExclusiveMinimumResolver` to define exclusive minimum values for number types, fields, or methods. This example handles `PositiveDecimal`, fields with `@Positive`, and methods with `@Minimum` (exclusive). ```java configBuilder.forTypesInGeneral() .withNumberExclusiveMinimumResolver(scope -> scope.getType().getErasedType() == PositiveDecimal.class ? BigDecimal.ZERO : null); configBuilder.forFields() .withNumberExclusiveMinimumResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(Positive.class) == null ? null : BigDecimal.ZERO); configBuilder.forMethods() .withNumberExclusiveMinimumResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Minimum.class)) .filter(Minimum::exclusive).map(Minimum::value).orElse(null)); ``` -------------------------------- ### Initialize Jackson Module and ConfigBuilder Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-jackson/README.md Instantiate the JacksonSchemaModule and pass it to the SchemaGeneratorConfigBuilder. This enables the module's features for schema generation. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.jackson.JacksonSchemaModule; ``` ```java JacksonSchemaModule module = new JacksonSchemaModule(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Initialize Swagger 2 Module Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_swagger-2-module.md Instantiate the Swagger2Module and add it to the SchemaGeneratorConfigBuilder to enable Swagger 2 annotation processing. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.swagger2.Swagger2Module; Swagger2Module module = new Swagger2Module(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Import Jackson Module and Configure Schema Generator Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-jackson/README.md Imports necessary classes and configures the SchemaGenerator with the JacksonSchemaModule and a chosen OptionPreset. ```java import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfig; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.jackson.JacksonSchemaModule; import tools.jackson.databind.JsonNode; ``` ```java JacksonSchemaModule module = new JacksonSchemaModule(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON) .with(module); SchemaGeneratorConfig config = configBuilder.build(); SchemaGenerator generator = new SchemaGenerator(config); JsonNode jsonSchema = generator.generateSchema(YourClass.class); System.out.println(jsonSchema.toString()); ``` -------------------------------- ### Configure Generator Options Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Customize generator behavior using `` with presets, enabled, and disabled options. Presets include NONE and FULL_DOCUMENTATION. Options like DEFINITIONS_FOR_ALL_OBJECTS can be enabled or disabled. ```xml com.myOrg.myApp.MyClass FULL_DOCUMENTATION SCHEMA_VERSION_INDICATOR ``` -------------------------------- ### Instantiate and Configure Swagger2Module Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-swagger-2/README.md Creates an instance of Swagger2Module and configures SchemaGeneratorConfigBuilder to use it. ```java Swagger2Module module = new Swagger2Module(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Configure 'description' Keyword Resolvers Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withDescriptionResolver` to specify how the 'description' attribute is generated for types, fields, or methods. The first non-null value returned by a resolver is applied. ```java configBuilder.forTypesInGeneral() .withDescriptionResolver(scope -> scope.getType().getErasedType() == YourClass.class ? "main schema description" : null); configBuilder.forFields() .withDescriptionResolver(field -> field.getType().getErasedType() == String.class ? "text field" : null); configBuilder.forMethods() .withDescriptionResolver(method -> method.getName().startsWith("get") ? "getter" : null); ``` -------------------------------- ### Enable and Disable Generator Options Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-options.md Demonstrates how to enable and disable specific schema generation options using the configBuilder. Use .with() to enable and .without() to disable. ```java configBuilder.with( Option.EXTRA_OPEN_API_FORMAT_VALUES, Option.PLAIN_DEFINITION_KEYS); configBuilder.without( Option.Schema_VERSION_INDICATOR, Option.ENUM_KEYWORD_FOR_SINGLE_VALUES); ``` -------------------------------- ### Generate Schema with Gradle Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_faq.md Demonstrates how to use the JSON Schema Generator library directly within a Gradle build script to generate a JSON schema. ```groovy import com.github.victools.jsonschema.generator.OptionPreset; import com.github.victools.jsonschema.generator.SchemaGenerator; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; buildscript { repositories { mavenCentral() } dependencies { classpath group: 'com.github.victools', name: 'jsonschema-generator', version: '4.16.0' } } plugins { id 'java-library' } task generate { doLast { def configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09, OptionPreset.PLAIN_JSON); // apply your configurations here def generator = new SchemaGenerator(configBuilder.build()); // target the class for which to generate a schema def jsonSchema = generator.generateSchema(SchemaVersion.class); // handle generated schema, e.g. write it to the console or a file def jsonSchemaAsString = jsonSchema.toPrettyString(); println jsonSchemaAsString new File(projectDir, "schema.json").text = jsonSchemaAsString } } ``` -------------------------------- ### Select Generator Options Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_maven-plugin.md Include standard generator options using the `` tag. Presets and specific options can be enabled or disabled. ```xml FULL_DOCUMENTATION SCHEMA_VERSION_INDICATOR ``` -------------------------------- ### Disabling Failure on No Matching Classes Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Sets the plugin to not abort the build if no classes match the specified selection rules, allowing for builds to complete even when no schemas are generated. ```xml false ``` -------------------------------- ### Configure Schema File Path Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Specify the directory where generated schema files will be placed using the `` element. The default path is 'src/main/resources'. ```xml com.myOrg.myApp.MyClass src/main/resources/schemas ``` -------------------------------- ### Define Module Options Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Configure specific options for a module, such as enabling 'FLATTENED_ENUMS_FROM_JSONVALUE' for the Jackson module. ```xml com.myOrg.myApp.MyClass Jackson ``` -------------------------------- ### Include Custom Module by Class Name Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_maven-plugin.md Include a custom module by specifying its fully qualified class name within the `` tag. Ensure the custom module is on the classpath and has a default constructor. ```xml com.myOrg.myApp.CustomModule ``` -------------------------------- ### Instantiate and Configure JavaxValidationModule Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-javax-validation/README.md Create an instance of JavaxValidationModule and add it to the SchemaGeneratorConfigBuilder. ```java JavaxValidationModule module = new JavaxValidationModule(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Plain Definition Keys Option Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-options.md Ensures that keys for $defs/definitions adhere to specific regular expressions, either matching OpenAPI 3.0 or JSON Schema specifications. ```markdown Option.PLAIN_DEFINITION_KEYS ``` -------------------------------- ### Configure Schema File Name with Class Directory Structure Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Store generated schema files in the same directory structure as their originating classes by using the package path variable {1} in ``. ```xml com.myOrg.myApp.utils {1}/{0}.schema ``` -------------------------------- ### Complete Maven Plugin Configuration Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md This snippet shows a comprehensive configuration for the jsonschema-maven-plugin within a Maven pom.xml file. It includes specifying class names, package names, schema version, file naming, schema path, and various options for object definitions, nullable fields, and module-specific settings like flattened enums. ```xml com.github.victools jsonschema-maven-plugin [4.21.0,5.0.0) generate com.myOrg.myApp.MyClass com.myOrg.myApp.MyOtherClass com.myOrg.myApp.utilities DRAFT_2019_09 {1}/{0}.schema result/schemas Jackson com.github.imifou.jsonschema.module.addon.AddonModule ``` -------------------------------- ### Selecting Classes Based on Annotations Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Configures the plugin to select classes for schema generation based on the presence of specified annotations. This allows for a more semantic approach to class selection. ```xml com.myOrg.myApp.MyAnnotation com.myOrg.myApp.MyOtherAnnotation ``` -------------------------------- ### Initialize SwaggerModule Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-swagger-1.5/README.md Instantiate the SwaggerModule and add it to the SchemaGeneratorConfigBuilder. This enables the module's functionality for generating JSON Schemas. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.swagger15.SwaggerModule; ``` ```java SwaggerModule module = new SwaggerModule(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Import JavaxValidationModule Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-javax-validation/README.md Import the JavaxValidationModule class to use it with the SchemaGeneratorConfigBuilder. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule; ``` -------------------------------- ### Configure Javax Validation Module Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_javax-validation-module.md Instantiate JavaxValidationModule with desired options and validation groups, then add it to the SchemaGeneratorConfigBuilder. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationOption; JavaxValidationModule module = new JavaxValidationModule(JavaxValidationOption.PREFER_IDN_EMAIL_FORMAT) .forValidationGroups(YourGroupFlag.class); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Configure string minLength for Types, Fields, and Methods Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use withStringMinLengthResolver to specify the minLength attribute based on scope. The first non-null value is applied. ```java configBuilder.forTypesInGeneral() .withStringMinLengthResolver(scope -> scope.getType().getErasedType() == UUID.class ? 36 : null); configBuilder.forFields() .withStringMinLengthResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(NotEmpty.class) == null ? null : 1); configBuilder.forMethods() .withStringMinLengthResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Size.class)) .map(Size::min).orElse(null)); ``` -------------------------------- ### Configure patternProperties for Types, Fields, and Methods Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use withPatternPropertiesResolver to map regular expressions to allowed types for different scopes. The first non-null value is applied. ```java configBuilder.forTypesInGeneral() .withPatternPropertiesResolver(scope -> scope.getType().isInstanceOf(Map.class) ? Collections.singletonMap("^[a-zA-Z]+$", scope.getTypeParameterFor(Map.class, 1)) : null); configBuilder.forFields() .withPatternPropertiesResolver(field -> field.getType().isInstanceOf(TypedMap.class) ? Collections.singletonMap("_int$", int.class) : null); configBuilder.forMethods() .withPatternPropertiesResolver(method -> method.getType().isInstanceOf(StringMap.class) ? Collections.singletonMap("^txt_$", String.class) : null); ``` -------------------------------- ### Set Individual Standard Options Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md Configure schema generation by directly setting individual standard options on the SchemaGeneratorConfigBuilder. This can be used alongside or instead of predefined OptionPresets. ```java import com.github.victools.jsonschema.generator.Option; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(Option.FLATTENED_ENUMS) .without(Option.NULLABLE_FIELDS_BY_DEFAULT, Option.NULLABLE_METHOD_RETURN_VALUES_BY_DEFAULT); ``` -------------------------------- ### Configuring Classpath Scope Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Specifies the scope of the classpath to consider for schema generation. Options include project only, compile dependencies, runtime dependencies, or all dependencies. ```xml PROJECT_ONLY ``` -------------------------------- ### Configure Schema File Name Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Customize the name of generated schema files using `` with `MessageFormat` syntax. Variables like {0} (class name) and {1} (package path) can be used. The default is '{0}-schema.json'. ```xml com.myOrg.myApp.MyClass {0}.schema ``` -------------------------------- ### Configure string format for Types, Fields, and Methods Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use withStringFormatResolver to specify the format attribute based on scope. The first non-null value is applied. ```java configBuilder.forTypesInGeneral() .withStringFormatResolver(scope -> scope.getType().getErasedType() == UUID.class ? "uuid" : null); configBuilder.forFields() .withStringFormatResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(Email.class) == null ? null : "email"); configBuilder.forMethods() .withStringFormatResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Schema.class)) .map(Schema::format).orElse(null)); ``` -------------------------------- ### Basic Plugin Definition Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Defines the jsonschema-maven-plugin in the Maven project's pom.xml to enable schema generation. It specifies the goal to execute and a basic configuration for class names. ```xml com.github.victools jsonschema-maven-plugin generate com.myOrg.myApp.MyClass ``` -------------------------------- ### Configure maxItems Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use withArrayMaxItemsResolver to set the 'maxItems' value based on type, field, or method scope. The first non-null value is applied. ```java configBuilder.forTypesInGeneral() .withArrayMaxItemsResolver(scope -> scope.getType().isInstanceOf(Triple.class) ? 3 : null); configBuilder.forFields() .withArrayMaxItemsResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(NoMoreThanADozen.class) == null ? null : 12); configBuilder.forMethods() .withArrayMaxItemsResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Size.class)) .map(Size::max).orElse(null)); ``` -------------------------------- ### Custom Enum Serialization Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_faq.md Shows how to use a custom serialization logic for enum values to generate the correct list of allowed values in the schema. ```java ObjectMapper objectMapper = new ObjectMapper(); // make use of your enum handling e.g. through your own serializer // objectMapper.registerModule(new YourCustomEnumSerializerModule()); configBuilder.with(new EnumModule(possibleEnumValue -> { try { String valueInQuotes = objectMapper.writeValueAsString(possibleEnumValue); return valueInQuotes.substring(1, valueInQuotes.length() - 1); } catch (JsonProcessingException ex) { throw new IllegalStateException(ex); } })); ``` -------------------------------- ### Reference Schema for Same Type (Collection) Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-advanced.md Use `createStandardDefinitionReference()` to include an unchanged schema of the same type, skipping the current definition provider to avoid infinite loops. ```java CustomDefinitionProviderV2 thisProvider = (javaType, context) -> javaType.isInstanceOf(Collection.class) ? new CustomDefinition( context.createStandardDefinitionReference(javaType, thisProvider), DefinitionType.STANDARD, AttributeInclusion.NO) : null; configBuilder.forTypesInGeneral() .withCustomDefinitionProvider(thisProvider); ``` -------------------------------- ### Configure 'default' Keyword Resolvers Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withDefaultResolver` to set the 'default' attribute for types, fields, or methods. The first non-null value is applied and serialized via the ObjectMapper. ```java configBuilder.forTypesInGeneral() .withDefaultResolver(scope -> scope.getType().getErasedType() == boolean.class ? Boolean.FALSE : null); configBuilder.forFields() .withDefaultResolver(field -> field.getType().getErasedType() == String.class ? "" : null); configBuilder.forMethods() .withDefaultResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetter(Default.class)) .map(Default::value).orElse(null)); ``` -------------------------------- ### Configure Type and Field Behavior Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md Define custom resolvers for schema attributes like 'title' and 'description' for types and fields. This allows for dynamic population of schema metadata based on Java type information. ```java import com.github.victools.jsonschema.generator.FieldScope; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.generator.TypeScope; SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09); configBuilder.forTypesInGeneral() // populate the "title" of all schemas with a description of the java type .withTitleResolver(TypeScope::getSimpleTypeDescription); configBuilder.forFields() // show the original field name as the "description" (may differ from the overridden property name in the schema) .withDescriptionResolver(FieldScope::getDeclaredName); ``` -------------------------------- ### Skipping Abstract Types and Interfaces Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Configures the plugin to skip the generation of JSON schemas for abstract classes and interfaces, which can be useful for focusing on concrete implementations. ```xml com/myOrg/myApp/package/** true true ``` -------------------------------- ### Configure Schema Version Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-maven-plugin/README.md Set the JSON Schema version using the `` element. Allowed values include DRAFT_2020_12, DRAFT_2019_09, DRAFT_7, and DRAFT_6. DRAFT_7 is the default. ```xml com.myOrg.myApp.MyClass DRAFT_2019_09 ``` -------------------------------- ### Populate Default Values from Instance Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_faq.md Determine default values for schema properties by invoking getters on instances of the declaring class. This method is useful when default values are set programmatically and should not be duplicated. ```java ConcurrentMap, Object> instanceCache = new ConcurrentHashMap<>(); configBuilder.forFields().withDefaultResolver(field -> { Class declaringClass = field.getDeclaringType().getErasedType(); if (!field.isFakeContainerItemScope() && declaringClass.getName().startsWith("your.package")) { MethodScope getter = field.findGetter(); if (getter != null) { try { Object instance = instanceCache.computeIfAbsent(declaringClass, declaringClass::newInstance); Object defaultValue = getter.getRawMember().invoke(instance); return defaultValue; } catch (Exception ex) { // most likely missing a no-args constructor } } } return null; }); ``` -------------------------------- ### Add Separate Modules Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-generator/README.md Incorporate external modules into the schema generation process by adding them to the SchemaGeneratorConfigBuilder. Refer to the main README for a list of available modules. ```java import com.github.victools.jsonschema.generator.Module; import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; Module separateModule = new YourSeparateModule(); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(separateModule); ``` -------------------------------- ### Custom Definition Naming Strategy Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Implement a custom strategy for naming definitions in JSON schemas, allowing control over duplicate names and nullable type suffixes. This strategy is applied to keys in the '$defs' or 'definitions' sections. ```java configBuilder.forTypesInGeneral() .withDefinitionNamingStrategy(new DefaultSchemaDefinitionNamingStrategy() { @Override public String getDefinitionNameForKey(DefinitionKey key, SchemaGenerationContext context) { return super.getDefinitionNameForKey(key, generationContext).toLowerCase(); } @Override public void adjustDuplicateNames(Map duplicateNames, SchemaGenerationContext context) { char suffix = 'a'; duplicateNames.entrySet().forEach(entry -> entry.setValue(entry.getValue() + "-" + suffix++)); } @Override public String adjustNullableName(DefinitionKey key, String definitionName, SchemaGenerationContext context) { return definitionName + "-nullable"; } }); ``` -------------------------------- ### Import Swagger2Module Source: https://github.com/victools/jsonschema-generator/blob/main/jsonschema-module-swagger-2/README.md Imports necessary classes for using Swagger2Module with SchemaGeneratorConfigBuilder. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.swagger2.Swagger2Module; ``` -------------------------------- ### Configure minItems Resolver Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use withArrayMinItemsResolver to define the 'minItems' value based on type, field, or method scope. The first non-null value is applied. ```java configBuilder.forTypesInGeneral() .withArrayMinItemsResolver(scope -> scope.getType().isInstanceOf(MandatoryList.class) ? 1 : null); configBuilder.forFields() .withArrayMinItemsResolver(field -> field .getAnnotationConsideringFieldAndGetterIfSupported(NotEmpty.class) == null ? null : 1); configBuilder.forMethods() .withArrayMinItemsResolver(method -> Optional .ofNullable(method.getAnnotationConsideringFieldAndGetterIfSupported(Size.class)) .map(Size::min).orElse(null)); ``` -------------------------------- ### Configure Jakarta Validation Module Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_jakarta-validation-module.md Instantiate the JakartaValidationModule, optionally specifying options like PREFER_IDN_EMAIL_FORMAT and filtering by validation groups. Then, add the module to the SchemaGeneratorConfigBuilder. ```java import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; import com.github.victools.jsonschema.generator.SchemaVersion; import com.github.victools.jsonschema.module.jakarta.validation.JakartaValidationModule; import com.github.victools.jsonschema.module.jakarta.validation.JakartaValidationOption; JakartaValidationModule module = new JakartaValidationModule(JakartaValidationOption.PREFER_IDN_EMAIL_FORMAT) .forValidationGroups(YourGroupFlag.class); SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2019_09) .with(module); ``` -------------------------------- ### Configure 'title' Keyword Resolvers Source: https://github.com/victools/jsonschema-generator/blob/main/slate-docs/source/includes/_main-generator-individual.md Use `withTitleResolver` to define how the 'title' attribute is generated for types, fields, or methods. The first non-null value returned by a resolver is applied. ```java configBuilder.forTypesInGeneral() .withTitleResolver(scope -> scope.getType().getErasedType() == YourClass.class ? "main schema title" : null); configBuilder.forFields() .withTitleResolver(field -> field.getType().getErasedType() == String.class ? "text field" : null); configBuilder.forMethods() .withTitleResolver(method -> method.getName().startsWith("get") ? "getter" : null); ```