### Full jsonschema2pojo Gradle Configuration Example Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md A comprehensive example of a build.gradle file demonstrating all available configuration options for the jsonschema2pojo plugin. This includes setting source and target directories, package names, annotation styles, and dependency inclusions. ```groovy plugins { id "java" id "org.jsonschema2pojo" version "1.3.3" } repositories { mavenCentral() } dependencies { // Required if generating JSR-303 annotations implementation 'javax.validation:validation-api:1.1.0.CR2' implementation 'jakarta.validation:jakarta.validation-api:3.0.0' // Required if generating Jackson 2 annotations implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' // Required if generating Jackson 3 annotations implementation 'tools.jackson.core:jackson-databind:3.0.2' // Required if generating JodaTime data types implementation 'joda-time:joda-time:2.2' } jsonSchema2Pojo { // Location of the JSON Schema file(s). This may refer to a single file or a directory of files. source = files("${sourceSets.main.output.resourcesDir}/json") // Target directory for generated Java source files. The plugin will add this directory to the // java source set so the compiler will find and compile the newly generated source files. targetDirectory = file("${project.buildDir}/generated-sources/js2p") // Package name used for generated Java classes (for types where a fully qualified name has not // been supplied in the schema using the 'javaType' property). targetPackage = '' // Whether to allow 'additional' properties to be supported in classes by adding a map to // hold these. This is true by default, meaning that the schema rule 'additionalProperties' // controls whether the map is added. Set this to false to globally disable additional properties. includeAdditionalProperties = false // Whether to include a javax.annotation.Generated (Java 8 and lower) or // javax.annotation.processing.Generated (Java 9+) in on generated types (default true). // See also: targetVersion. includeGeneratedAnnotation = true // Whether to generate builder-style methods of the form withXxx(value) (that return this), // alongside the standard, void-return setters. generateBuilders = false // If set to true, then the gang of four builder pattern will be used to generate builders on // generated classes. Note: This property works in collaboration with generateBuilders. // If generateBuilders is false then this property will not do anything. useInnerClassBuilders = false // Whether to use primitives (long, double, boolean) instead of wrapper types where possible // when generating bean properties (has the side-effect of making those properties non-null). usePrimitives = false // The characters that should be considered as word delimiters when creating Java Bean property // names from JSON property names. If blank or not set, JSON properties will be considered to // contain a single word when creating Java Bean property names. propertyWordDelimiters = [] as char[] // Whether to use the java type long (or Long) instead of int (or Integer) when representing the // JSON Schema type 'integer'. useLongIntegers = false // Whether to use the java type BigInteger when representing the JSON Schema type 'integer'. Note // that this configuration overrides useLongIntegers useBigIntegers = false // Whether to use the java type double (or Double) instead of float (or Float) when representing the // JSON Schema type 'number'. useDoubleNumbers = true // Whether to use the java type BigDecimal when representing the JSON Schema type 'number'. Note // that this configuration overrides useDoubleNumbers useBigDecimals = false // Whether to include hashCode and equals methods in generated Java types. includeHashcodeAndEquals = true // Whether to include a toString method in generated Java types. includeToString = true // The style of annotations to use in the generated Java types. Supported values: // - jackson (alias of jackson2) // - jackson2 (apply annotations from the Jackson 2.x library) // - jackson3 (apply annotations from the Jackson 3.x library) // - jsonb (apply annotations from the JSON-B 1 library) // - jsonb2 (apply annotations from the JSON-B 2 library) // - gson (apply annotations from the Gson library) // - moshi1 (apply annotations from the Moshi 1.x library) // - none (apply no annotations at all) annotationStyle = 'jackson' // A fully qualified class name, referring to a custom annotator class that implements } ``` -------------------------------- ### Example of Cyclic anyOf Schema Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Proposal-for-allOf,-anyOf-and-oneOf A schema demonstrating deep recursion using anyOf, which can lead to complex type hierarchies that require collapsing strategies for effective code generation. ```json { "type": "object", "properties": { "child": { "anyOf": [ { "ref": "#/definitions/a" }, { "ref": "#/definitions/b" } ] } }, "definitions": { "a": { "type": "object", "properties": { "child": { "ref": "#/definitions/c" }, "a": { "type": "string" } } }, "b": { "type": "object", "properties": { "child": { "ref": "#/definitions/d" }, "b": { "type": "string" } } }, "c": { "type": "object", "properties": { "child": { "ref": "#/definitions/a" }, "c": { "type": "string" } } }, "d": { "type": "object", "properties": { "child": { "ref": "#/definitions/e" }, "d": { "type": "string" } } }, "e": { "type": "object", "properties": { "child": { "ref": "#/definitions/b" }, "e": { "type": "string" } } } } } ``` -------------------------------- ### Integrate jsonschema2pojo Gradle Plugin Locally Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Steps to integrate the jsonschema2pojo Gradle plugin into a local project. This involves installing the plugin locally via Maven and configuring the build.gradle file to use the local dependency. ```groovy buildscript { repositories { mavenLocal() } dependencies { classpath 'org.jsonschema2pojo:jsonschema2pojo-gradle-plugin:latest.integration' } } repositories { mavenLocal() } ``` -------------------------------- ### JSON Schema Example for Deep References Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Proposal-for-allOf,-anyOf-and-oneOf Illustrates two JSON schemas where a nested object 'child' is defined differently due to an 'allOf' applicator in one schema and a deep reference in another. This highlights the challenge of generating distinct types for the same schema fragment. ```json { "$id": "a.json", "type": "object", "properties": { "child": { "type": "object", "properties": { "grandchild": { "type": "string" } } } }, "allOf": [ "properties": { "child": { "properties": { "grandchild": { "format": "date-time" } } } } ] } ``` ```json { "$id": "b.json", "type": "object", "properties": { "child": { "$ref": "a.json#/properties/child" } } } ``` -------------------------------- ### Example of Nested oneOf in allOf Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Proposal-for-allOf,-anyOf-and-oneOf A schema snippet demonstrating the nesting of multiple oneOf constraints within an allOf block, which requires specific flattening rules to avoid combinatorial explosions. ```json { "allOf": [ { "oneOf": [ { "ref": "a.json" }, { "ref": "b.json" } ], "oneOf": [ { "ref": "c.json" }, { "ref": "d.json" } ] } ] } ``` -------------------------------- ### Java Code Example for jsonschema2pojo Generation Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started This Java code demonstrates how to use the jsonschema2pojo API to generate Java classes from a JSON schema. It configures the generation process, including enabling builder generation, and outputs the generated code to a temporary directory. ```java JCodeModel codeModel = new JCodeModel(); URL source = Example.class.getResource("/schema/required.json"); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { return true; } }; SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator()); mapper.generate(codeModel, "ClassName", "com.example", source); codeModel.build(Files.createTempDirectory("required").toFile()); ``` -------------------------------- ### Generated Java Enum Implementation Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Example of the Java code generated from the priority enum schema, including JSON serialization and deserialization support. ```java public enum Priority { LOW("L"), MEDIUM("M"), HIGH("H"); private final String value; Priority(String value) { this.value = value; } @JsonValue public String toString() { return this.value; } @JsonCreator public static Priority fromValue(String value) { for (Priority p : Priority.values()) { if (p.value.equals(value)) return p; } throw new IllegalArgumentException(value); } } ``` -------------------------------- ### Java Class with Additional Properties and Dynamic Accessors Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Demonstrates a Java class generated with support for additional properties and dynamic accessors. It includes Jackson annotations (@JsonAnyGetter, @JsonAnySetter) for handling arbitrary properties and custom methods (get, set, with) for runtime manipulation. This pattern is useful for flexible data handling. ```java import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.LinkedHashMap; import java.util.Map; public class FlexibleObject { @JsonProperty("name") private String name; @JsonProperty("type") private String type; @JsonIgnore private Map additionalProperties = new LinkedHashMap<>(); // Standard getters and setters for name and type... @JsonAnyGetter public Map getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, String value) { this.additionalProperties.put(name, value); } // Dynamic accessors public Object get(String name) { switch (name) { case "name": return getName(); case "type": return getType(); default: return getAdditionalProperties().get(name); } } public void set(String name, Object value) { switch (name) { case "name": setName((String) value); break; case "type": setType((String) value); break; default: setAdditionalProperty(name, (String) value); } } public FlexibleObject with(String name, Object value) { set(name, value); return this; } } // Usage: // FlexibleObject obj = new FlexibleObject() // .withName("example") // .withType("demo") // .with("customField", "customValue") // .with("anotherField", "anotherValue"); // String custom = (String) obj.get("customField"); // "customValue" ``` -------------------------------- ### Collapsed Cyclic Schema Representation Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Proposal-for-allOf,-anyOf-and-oneOf The resulting schema after applying type collapsing to the cyclic anyOf example to simplify the generated object structure. ```json { "type": "object", "properties": { "child": { "type": "object", "properties": { "child": { "ref": "#/properties/child" }, "a": { "type": "string" }, "b": { "type": "string" }, "c": { "type": "string" }, "d": { "type": "string" }, "e": { "type": "string" } } } } } ``` -------------------------------- ### Execute Full Build and Test Suite Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/CONTRIBUTING.md Runs the complete build lifecycle including cleaning the target directory, compiling source code, executing unit tests, packaging the application, and running the full integration test suite. ```bash ./mvnw clean verify ``` -------------------------------- ### Implement Builder Pattern for Java POJOs Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Shows how to enable and use the builder pattern in generated Java classes to allow for fluent object initialization. ```java public MyObject withFoo(String foo) { this.foo = foo; return this; } // Usage: MyObject o = new MyObject().withFoo("foo").withBar("bar").withBaz("baz"); ``` -------------------------------- ### Execute jsonschema2pojo via Command Line Interface Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt These commands demonstrate how to use the jsonschema2pojo CLI to generate Java classes from JSON or JSON Schema files. It covers basic usage, advanced configuration flags, and help/version commands. ```bash # Basic usage jsonschema2pojo --source address.json --target java-gen --package com.example.types # Generate with Jackson 2 and builders jsonschema2pojo --source ./schemas/ --target ./src/main/java --package com.example.model --annotation-style jackson2 --generate-builders --generate-constructors # Generate from JSON example jsonschema2pojo --source example.json --target ./generated --package com.example --source-type json # Full featured generation with validation jsonschema2pojo --source ./schemas --target ./generated-sources --package com.example.api.model --annotation-style jackson2 --generate-builders --generate-constructors --constructors-include-all-properties-constructor --jsr303-annotations --useJakartaValidation --include-dynamic-accessors --datetime-class java.time.OffsetDateTime --date-class java.time.LocalDate --time-class java.time.LocalTime --format-date-times --serializable # Generate with Gson annotations jsonschema2pojo --source schema.json --target ./out --package com.example --annotation-style gson # Help and version jsonschema2pojo --help jsonschema2pojo --version ``` -------------------------------- ### Initialize Collections - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Configures whether Set and List fields should be initialized as empty collections or left as null upon generation. ```java initializeCollections = true ``` -------------------------------- ### Generate Java Classes with Schema References and Inheritance Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Illustrates using JSON schema's `$ref` for referencing other schemas and `extends` for implementing inheritance. This allows for modular schema definitions and the creation of class hierarchies in generated Java code. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Order", "type": "object", "properties": { "orderId": { "type": "string" }, "customer": { "$ref": "customer.json" }, "shippingAddress": { "$ref": "#/definitions/Address" }, "billingAddress": { "$ref": "#/definitions/Address" }, "items": { "type": "array", "items": { "$ref": "#/definitions/OrderItem" } } }, "definitions": { "Address": { "type": "object", "properties": { "street": { "type": "string" }, "city": { "type": "string" }, "country": { "type": "string" }, "postalCode": { "type": "string" } }, "required": ["street", "city", "country"] }, "OrderItem": { "type": "object", "properties": { "productId": { "type": "string" }, "quantity": { "type": "integer", "minimum": 1 }, "unitPrice": { "type": "number" } } } } } ``` ```json { "title": "Vehicle", "type": "object", "properties": { "make": { "type": "string" }, "model": { "type": "string" }, "year": { "type": "integer" } } } ``` ```json { "title": "Car", "type": "object", "extends": { "$ref": "vehicle.json" }, "properties": { "numberOfDoors": { "type": "integer" }, "trunkCapacity": { "type": "number" } } } ``` ```java public class Vehicle { private String make; private String model; private Integer year; // ... } public class Car extends Vehicle { private Integer numberOfDoors; private Double trunkCapacity; // ... } ``` -------------------------------- ### Schema References and Inheritance Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Using $ref for composition and the extends keyword for class inheritance in generated Java models. ```APIDOC ## POST /schema/compose ### Description Allows for modular schema design using $ref for external/internal definitions and 'extends' for implementing class inheritance hierarchies. ### Method POST ### Endpoint /schema/compose ### Request Body - **$ref** (string) - Optional - URI to a referenced schema definition. - **extends** (object) - Optional - Reference to a parent schema for inheritance. - **definitions** (object) - Optional - Reusable schema components. ### Request Example { "title": "Car", "type": "object", "extends": { "$ref": "vehicle.json" }, "properties": { "numberOfDoors": { "type": "integer" } } } ### Response #### Success Response (200) - **classDefinition** (string) - The generated Java class extending the parent class. ``` -------------------------------- ### Java Enum Generation from JSON Schema Enum Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Generates a Java enum type from a JSON Schema 'enum' declaration. The enum constants hold the original enum values and are annotated for Jackson serialization/deserialization. This handles cases where enum values contain spaces or start with digits. ```json { "type" : "object", "properties" : { "myEnum" : { "type" : "string", "enum" : ["one", "secondOne", "3rd one"] } } } ``` ```java @Generated("com.googlecode.jsonschema2pojo") public static enum MyEnum { ONE("one"), SECOND_ONE("secondOne"), _3_RD_ONE("3rd one"); private final String value; private MyEnum(String value) { this.value = value; } @JsonValue @Override public String toString() { return this.value; } @JsonCreator public static MyObject.MyEnum fromValue(String value) { for (MyObject.MyEnum c: MyObject.MyEnum.values()) { if (c.value.equals(value)) { return c; } } throw new IllegalArgumentException(value); } } ``` -------------------------------- ### jsonschema2pojo Format Rule to Java Type Mapping Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference The 'format' rule in a JSON schema can influence the Java type chosen for a property. When jsonschema2pojo recognizes a format value, it uses a more appropriate Java type. For example, a string with format 'uri' becomes java.net.URI instead of java.lang.String. ```json { "type": "string", "format": "uri" } ``` -------------------------------- ### Apply jsonschema2pojo Plugin with Gradle 7.3+ (Groovy) Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Demonstrates how to apply the jsonschema2pojo Gradle plugin using the plugins DSL in a Groovy build script. This method is recommended for Gradle 7.3 and later. ```groovy plugins { id "java" id "org.jsonsonschema2pojo" version "1.3.3" } jsonSchema2Pojo { ... } ``` -------------------------------- ### Configure jsonschema2pojo Gradle Plugin Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt This snippet demonstrates how to apply the jsonschema2pojo plugin in a build.gradle file. It includes necessary dependencies and a comprehensive configuration block for customizing generated Java classes. ```groovy plugins { id "java" id "org.jsonschema2pojo" version "1.3.3" } repositories { mavenCentral() } dependencies { implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' implementation 'org.apache.commons:commons-lang3:3.12.0' implementation 'jakarta.validation:jakarta.validation-api:3.0.0' } jsonSchema2Pojo { source = files("${sourceSets.main.output.resourcesDir}/json") targetDirectory = file("${project.buildDir}/generated-sources/js2p") targetPackage = 'com.example.types' sourceType = 'jsonschema' annotationStyle = 'jackson2' generateBuilders = true includeConstructors = true includeAllPropertiesConstructor = true includeRequiredPropertiesConstructor = true includeHashcodeAndEquals = true includeToString = true includeJsr303Annotations = true useJakartaValidation = true dateTimeType = "java.time.LocalDateTime" dateType = "java.time.LocalDate" timeType = "java.time.LocalTime" formatDateTimes = true formatDates = true formatTimes = true includeAdditionalProperties = true useDoubleNumbers = true includeGetters = true includeSetters = true serializable = true } ``` -------------------------------- ### Configure Custom Date and Timezone Patterns Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Demonstrates how to use customPattern and customDateTimePattern within a JSON schema to influence serialization annotations like @JsonFormat. It also shows how to specify a custom timezone for date-time fields. ```json { "type" : "object", "properties" : { "dob" : { "type" : "string", "format" : "date", "customPattern" : "yy-MM-dd" }, "updatedDate" : { "type" : "string", "format" : "date-time", "customDateTimePattern" : "yyyy-MM-dd'T'HH:mm:ssZ", "customTimezone": "PDT" } } } ``` -------------------------------- ### Configure Enums and Custom Type Mappings Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Shows how to define custom Java enum names, map JSON fields to specific Java types, and use existing Java types for complex objects or collections. ```json { "type": "object", "properties": { "status": { "type": "string", "enum": ["pending", "in_progress", "completed", "cancelled"], "javaEnumNames": ["PENDING", "IN_PROGRESS", "COMPLETED", "CANCELLED"] }, "priority": { "type": "string", "enum": ["L", "M", "H"], "javaEnums": [ { "name": "LOW", "title": "Low Priority", "description": "Tasks that can wait" }, { "name": "MEDIUM", "title": "Medium Priority", "description": "Standard priority tasks" }, { "name": "HIGH", "title": "High Priority", "description": "Urgent tasks requiring immediate attention" } ] }, "customId": { "javaType": "com.example.CustomIdentifier", "type": "string" }, "legacyData": { "existingJavaType": "java.util.Map", "type": "object" }, "tags": { "existingJavaType": "java.util.Set", "type": "array" } } } ``` -------------------------------- ### Configure jsonschema2pojo Gradle Plugin Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/README.md This snippet demonstrates how to configure the jsonschema2pojo Gradle plugin in a build.gradle file. It includes applying the plugin, setting up repositories, and defining the target package for generated Java types. This configuration enables automatic generation of Java classes from JSON schemas during the Gradle build process. ```groovy plugins { id "java" id "org.jsonschema2pojo" version "1.3.3" } repositories { mavenCentral() } jsonSchema2Pojo { targetPackage = 'com.example' } ``` -------------------------------- ### Apply jsonschema2pojo Plugin with Gradle 7.3+ (Kotlin) Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Shows how to apply the jsonschema2pojo Gradle plugin using the plugins DSL in a Kotlin build script. This is the modern approach for Gradle 7.3 and newer. ```kotlin plugins { id("java") id("org.jsonschema2pojo") version "1.3.3" } jsonSchema2Pojo { ... } ``` -------------------------------- ### Dynamic Accessors Configuration Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Enable support for additional properties and dynamic accessors to handle flexible JSON structures at runtime. ```APIDOC ## Dynamic Accessors Configuration ### Description Configure the generator to include dynamic getters, setters, and builders for handling additional properties in JSON schemas. ### Method N/A (Gradle/Maven Configuration) ### Parameters #### Configuration Fields - **includeAdditionalProperties** (boolean) - Required - Enables storage of unknown properties in a map. - **includeDynamicAccessors** (boolean) - Required - Enables generic get/set/with methods for property access. ### Response Example ```java // Generated dynamic access public Object get(String name) { ... } public void set(String name, Object value) { ... } ``` ``` -------------------------------- ### Generate Java Types via jsonschema2pojo CLI Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started This command invokes the jsonschema2pojo command-line interface to generate Java types. It takes the source directory containing JSON schemas and the target directory for the generated Java files as arguments. ```bash jsonschema2pojo --source address --target java-gen ``` -------------------------------- ### Map JSON Fields to Custom Java Names Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Demonstrates how to override default field naming conventions using the javaName property. ```json { "type": "object", "properties": { "api_key": { "javaName": "apiKey", "type": "string" }, "created_at": { "javaName": "createdAt", "type": "string", "format": "date-time" } } } ``` -------------------------------- ### Generate POJOs from JSON Schema using Java API Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt This Java code demonstrates how to use the jsonschema2pojo programmatic API to generate Plain Old Java Objects (POJOs) from JSON schemas at runtime. It shows how to configure generation options like annotation style, builder generation, and constructor inclusion, and how to provide schemas via URL or inline strings. The generated code is then written to a temporary directory. ```java import com.sun.codemodel.JCodeModel; import org.jsonschema2pojo.*; import org.jsonschema2pojo.rules.RuleFactory; import java.io.File; import java.net.URL; import java.nio.file.Files; public class SchemaGenerator { public static void main(String[] args) throws Exception { // Create the code model to hold generated types JCodeModel codeModel = new JCodeModel(); // Configure generation options GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { return true; } @Override public AnnotationStyle getAnnotationStyle() { return AnnotationStyle.JACKSON2; } @Override public boolean isIncludeConstructors() { return true; } @Override public boolean isIncludeJsr303Annotations() { return true; } @Override public boolean isUseJakartaValidation() { return true; } @Override public String getDateTimeType() { return "java.time.OffsetDateTime"; } @Override public String getDateType() { return "java.time.LocalDate"; } @Override public boolean isSerializable() { return true; } }; // Create the schema mapper with configured annotator SchemaMapper mapper = new SchemaMapper( new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator() ); // Generate from URL (file, http, or classpath resource) URL schemaUrl = SchemaGenerator.class.getResource("/schemas/user.json"); mapper.generate(codeModel, "User", "com.example.model", schemaUrl); // Generate from inline JSON Schema string String addressSchema = "{\"type\": \"object\",\"properties\": {\"street\": { \"type\": \"string\" },\"city\": { \"type\": \"string\" },\"zipCode\": { \"type\": \"string\", \"pattern\": \"^[0-9]{5}$\" } },\"required\": [\"street\", \"city\"] }" ; mapper.generate(codeModel, "Address", "com.example.model", addressSchema); // Write generated sources to output directory File outputDir = Files.createTempDirectory("generated").toFile(); codeModel.build(outputDir); System.out.println("Generated sources written to: " + outputDir.getAbsolutePath()); } } ``` -------------------------------- ### Configure additionalProperties in Java POJOs Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Demonstrates how the additionalProperties schema rule affects Java class generation. It shows how the tool creates a Map field with Jackson annotations to handle dynamic JSON properties. ```json { "type" : "object", "additionalProperties" : {} } ``` ```java public class MyObject { private java.util.Map additionalProperties = new java.util.HashMap(); @org.codehaus.jackson.annotate.JsonAnyGetter public java.util.Map getAdditionalProperties() { return this.additionalProperties; } @org.codehaus.jackson.annotate.JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } } ``` -------------------------------- ### Include All Properties Constructor - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Adds a constructor that includes all fields, in addition to other generated constructors. Irrelevant if 'constructorsRequiredPropertiesOnly' is true. ```java includeAllPropertiesConstructor = false ``` -------------------------------- ### Define File Extensions to Ignore - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md An array of strings representing file extensions that should be ignored and not included in generated class names. ```java fileExtensions = [] as String[] ``` -------------------------------- ### Configure jsonschema2pojo Maven Plugin Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/README.md This snippet shows how to configure the jsonschema2pojo Maven plugin within a pom.xml file. It specifies the source directory for JSON schemas and the target package for the generated Java types. Ensure the plugin version is compatible with your project. ```xml org.jsonschema2pojo jsonschema2pojo-maven-plugin 1.3.3 ${basedir}/src/main/resources/schema com.example.types generate ``` -------------------------------- ### Reference Existing Java Types with Generics Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Illustrates the use of the existingJavaType property to map a schema property to a pre-existing Java class, including support for generic type arguments like Map. ```json { "type" : "object", "properties" : { "myProperty" : { "existingJavaType" : "java.util.Map", "type" : "object" } } } ``` -------------------------------- ### Define object-based additionalProperties Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Demonstrates how setting additionalProperties to an object type results in a Map using a custom generated class as the value type. ```json { "type" : "object", "additionalProperties" : { "type" : "object" } } ``` ```java public class MyObject { private java.util.Map additionalProperties = new java.util.HashMap(); @org.codehaus.jackson.annotate.JsonAnyGetter public java.util.Map getAdditionalProperties() { return this.additionalProperties; } @org.codehaus.jackson.annotate.JsonAnySetter public void setAdditionalProperties(String name, MyObjectProperty value) { this.additionalProperties.put(name, value); } } ``` -------------------------------- ### Configure JSR-303 Validation for BigDecimal Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Demonstrates how to define a minimum constraint in a JSON schema for a property mapped to a BigDecimal type, which triggers the generation of @DecimalMin annotations. ```json { "type" : "object", "properties" : { "minimum" : { "existingJavaType" : "java.math.BigDecimal", "minimum" : 1 } } } ``` -------------------------------- ### Configure jsonschema2pojo Options Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Configures various aspects of the jsonschema2pojo code generation, such as including setters, handling date/time formats, and specifying target Java versions. These options control the generated Java code's structure and behavior. ```groovy jsonschema2pojo { includeSetters = true includeDynamicAccessors = false includeDynamicGetters = false includeDynamicSetters = false includeDynamicBuilders = false useJodaLocalDates = false useJodaLocalTimes = false dateType = "java.time.LocalDate" dateTimeType = "java.time.LocalDateTime" timeType = "java.time.LocalTime" customDatePattern = "yyyy-MM-dd" customDateTimePattern = "yyyy-MM-dd HH:mm" customTimePattern = "HH:mm" formatTypeMapping = [] refFragmentPathDelimiters = "#/." includeJsonTypeInfoAnnotation = false useOptionalForGetters = false toStringExcludes = ["someProperty"] targetVersion = "1.8" fileFilter = new AllFileFilter() sourceSortOrder = SourceSortOrder.OS useJakartaValidation = false } ``` -------------------------------- ### Include Copy Constructor - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Adds a constructor that takes the class itself as a parameter, copying all properties from the originating class. Irrelevant if 'constructorsRequiredPropertiesOnly' is true. ```java includeCopyConstructor = false ``` -------------------------------- ### Generate Java POJO from JSON Schema Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Demonstrates the transformation of a simple JSON schema object definition into a corresponding Java class with private fields, getters, and setters. ```json { "type" : "object", "properties" : { "foo" : { "type" : "string" } } } ``` ```java public class MyObject { private String foo; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } } ``` -------------------------------- ### Custom Annotators and Rule Factories Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Configure custom annotators to inject annotations (like Lombok) and rule factories to modify the core generation logic. ```APIDOC ## Custom Annotators and Rule Factories ### Description Extend jsonschema2pojo behavior by implementing custom annotators for additional annotations or custom rule factories for modified generation logic. ### Method N/A (Configuration API) ### Parameters #### Request Body - **customAnnotator** (Class) - Optional - Implementation of AbstractAnnotator to add custom annotations to generated classes. - **customRuleFactory** (Class) - Optional - Implementation of RuleFactory to override default generation rules. ### Request Example ```java GenerationConfig config = new DefaultGenerationConfig() { @Override public Class getCustomAnnotator() { return LombokAnnotator.class; } }; ``` ``` -------------------------------- ### Configure jsonschema2pojo Maven Plugin Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started This configuration adds the jsonschema2pojo-maven-plugin to your pom.xml. It specifies the source directory for JSON schemas and the target package for generated Java types. The plugin is bound to the 'generate-sources' phase by default. ```xml org.jsonschema2pojo jsonschema2pojo-maven-plugin 1.3.3 ${basedir}/src/main/resources/schema com.example.types generate ``` -------------------------------- ### Defining JSON Schema Properties Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt How to define a JSON schema with various data types, constraints, and required fields to map to Java classes. ```APIDOC ## POST /schema/generate ### Description Defines a JSON schema document that maps to a strongly-typed Java class. Supports primitives, objects, arrays, and validation constraints. ### Method POST ### Endpoint /schema/generate ### Request Body - **title** (string) - Required - The name of the generated class. - **type** (string) - Required - The JSON type (e.g., object). - **properties** (object) - Required - Map of field names to their type definitions and constraints. - **required** (array) - Optional - List of mandatory fields. ### Request Example { "title": "User", "type": "object", "properties": { "id": { "type": "integer" }, "username": { "type": "string", "minLength": 3 } }, "required": ["id", "username"] } ### Response #### Success Response (200) - **classDefinition** (string) - The generated Java source code string. ``` -------------------------------- ### Gradle Configuration for Dynamic Accessors Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Configures jsonschema2pojo generation in Gradle to include support for additional properties and dynamic accessors. This allows the generated Java classes to handle arbitrary key-value pairs at runtime, making them flexible for dynamic JSON structures. Requires jsonschema2pojo Gradle plugin. ```groovy jsonSchema2Pojo { targetPackage = 'com.example' includeAdditionalProperties = true includeDynamicAccessors = true includeDynamicGetters = true includeDynamicSetters = true includeDynamicBuilders = true } ``` -------------------------------- ### Map array items to Java collections Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference Illustrates how the 'items' rule in JSON Schema determines the generic type of List or Set collections in the generated Java class. ```json { "type" : "object", "properties" : { "myArrayProperty" : { "type" : "array", "items" : { "type" : "string" } } } } ``` -------------------------------- ### Set Class Name Prefix - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Specifies a string to be added as a prefix to all generated Java class names. ```java classNamePrefix = "" ``` -------------------------------- ### Constructors Require Only Properties - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md If true, generated constructors will only include 'required' fields. This setting makes 'includeRequiredPropertiesConstructor', 'includeAllPropertiesConstructor', and 'includeCopyConstructor' irrelevant. ```java constructorsRequiredPropertiesOnly = false ``` -------------------------------- ### Include Constructors - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Determines whether constructors should be generated for the Java types. ```java includeConstructors = false ``` -------------------------------- ### Set Output File Encoding - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Defines the character encoding to be used when writing the generated Java source files. 'UTF-8' is a common and recommended setting. ```java outputEncoding = 'UTF-8' ``` -------------------------------- ### Include Getters - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Controls whether getter methods should be generated for the fields in the Java types. If false, public fields will be created instead. ```java includeGetters = true ``` -------------------------------- ### Remove Old Output Directory - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md When enabled, this option will delete the entire contents of the target directory before generating new source files. Use with caution as it can lead to data loss. ```java removeOldOutput = false ``` -------------------------------- ### Add jsonschema2pojo Maven Dependencies Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started These are the necessary dependencies for the generated Java types to compile. Commons Lang is required for utility methods like equals, hashCode, and toString, while Jackson annotations are used for JSON parsing hints. ```xml commons-lang commons-lang 2.4 com.fasterxml.jackson.core jackson-databind 2.5.4 ``` -------------------------------- ### Set Java Source/Target Version for Maven Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Getting-Started Ensures that the generated Java types are compatible with Java 6. This configuration should be added to the section of your pom.xml, specifically within the maven-compiler-plugin. ```xml org.apache.maven.plugins maven-compiler-plugin 1.6 1.6 ``` -------------------------------- ### Maven Plugin Configuration for jsonschema2pojo Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Configures the jsonschema2pojo Maven plugin to generate Java sources from JSON Schema files. It specifies source directories, target packages, annotation styles (e.g., Jackson2), and generation options like builders and JSR-303 annotations. ```xml org.jsonschema2pojo jsonschema2pojo-maven-plugin 1.3.3 ${basedir}/src/main/resources/schema com.example.types true jackson2 true true jsonschema true java.time.LocalDateTime java.time.LocalDate java.time.LocalTime generate com.fasterxml.jackson.core jackson-databind 2.15.2 org.apache.commons commons-lang3 3.12.0 jakarta.validation jakarta.validation-api 3.0.0 ``` -------------------------------- ### Java Code Generation with jsonschema2pojo for Jackson Source: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Proposal-for-allOf,-anyOf-and-oneOf A Java code snippet demonstrating the use of jsonschema2pojo to generate Java models from a JSON schema. It configures the generation process, including enabling builders and specifying the source type as JSON, and handles potential IO exceptions during file operations. ```java JCodeModel codeModel = new JCodeModel(); try { URL source= new URL("file:src/main/resources/schema/DummyApi.json"); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { return true; } public SourceType getSourceType(){ return SourceType.JSON; } }; SchemaMapper mapper =new SchemaMapper(new RuleFactory(config, new GsonAnnotator(config), new SchemaStore()), new SchemaGenerator()); mapper.generate(codeModel, "Accession", "com.pojogenerated", source); File dir = new File("src/main/java"); if(dir.exists()){ System.out.println("dir available"); codeModel.build(dir); }else{ System.out.println("dir not available"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ``` -------------------------------- ### Generated Java Class with Validation Source: https://context7.com/joelittlejohn/jsonschema2pojo/llms.txt Shows the resulting Java class containing JSR-303 annotations like @NotNull, @Pattern, and @Size based on the schema constraints. ```java public class UserProfile { @JsonProperty("email") @NotNull @Pattern(regexp = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$") private String email; @JsonProperty("username") @NotNull @Size(min = 3, max = 30) private String username; @JsonProperty("age") @DecimalMin("18") @DecimalMax("120") private Integer age; @JsonProperty("score") @DecimalMin("0.0") @DecimalMax("100.0") private BigDecimal score; @JsonProperty("tags") @Size(min = 1, max = 10) @Valid private List tags = new ArrayList<>(); @JsonProperty("phoneNumber") @Pattern(regexp = "^\\+?[1-9]\\d{1,14}$") private String phoneNumber; } ``` -------------------------------- ### Include Setters - Java Source: https://github.com/joelittlejohn/jsonschema2pojo/blob/master/jsonschema2pojo-gradle-plugin/README.md Controls whether setter methods should be generated for the fields in the Java types. If false, public fields will be created instead. ```java includeSetters = true ```