Jsonschema2Pojo

Description

jsonschema2pojo uses the structural rules present in a JSON Schema document to generate DTO style Java classes.

Parameters

Attribute Description Required
source The input JSON schema. Yes
targetDirectory The directory that generated .java source files will be saved to. Yes
annotationStyle The style of annotations to use in the generated Java types. Supported values:
  • JACKSON2 (apply annotations from the Jackson 2.x library)
  • JACKSON (alias for JACKSON2)
  • JSONB (apply annotations from the JSON-B 1.x library)
  • JSONB2 (apply annotations from the JSON-B 2.x library)
  • GSON (apply annotations from the Gson library)
  • MOSHI1 (apply annotations from the Moshi 1.x library)
  • NONE (apply no annotations at all)
No (default JACKSON2)
useTitleAsClassname When set the title is used as classname. No (default false)
inclusionLevel The level of inclusion to be set for generated java types (to control level of inclusion in case of Jackson serializer). Each level will have its own set of mapping annotations. Supported values:
  • ALWAYS Value that indicates that property is to be always included, independent of value of the property.
  • NON_ABSENT Value that indicates that properties are included unless their value is: null "absent" value of a referential type (like Java 8 `Optional`, or {link java.utl.concurrent.atomic.AtomicReference}); that is, something that would not deference to a non-null value.
  • NON_DEFAULT Meaning of this setting depends on context: whether annotation is specified for POJO type (class), or not.
  • NON_EMPTY Value that indicates that only properties with null value, or what is considered empty, are not to be included.
  • NON_NULL Value that indicates that only properties with non-null values are to be included.
  • USE_DEFAULTS Pseudo-value used to indicate that the higher-level defaults make sense, to avoid overriding inclusion value.
Default value NON_NULL)
classNamePrefix Whether to add a prefix to generated classes No (default "")
classNameSuffix Whether to add a suffix to generated classes No (default "")
fileExtensions A string containing file extensions that should be considered full extensions and therefore ignored when generating classnames. No (default "" (none))
classpath Additional classpath to use. Any path elements provided here will be added to the classpath when this task is invoked.

If a support for filesets/filelists/dirsets etc is required, this property can also be set as a nested element like:

<jsonschema2pojo ...
    <classpath>
        <fileset dir="custom-libs">
            <include name="**/*.jar" />
        </fileset>
    </classpath>
<jsonschema2pojo/>
No
classpathRef Additional classpath to use, given as a reference to a path defined elsewhere. Can be used in conjuction with the classpath option (the result is the union of all paths). No
customAnnotator

A fully qualified class name, referring to a custom annotator class that implements org.jsonschema2pojo.Annotator and will be used in addition to the one chosen by annotationStyle.

If you want to use the custom annotator alone, set annotationStyle to none.

No
customRuleFactory

A fully qualified class name, referring to a custom rule factory class that extends org.jsonschema2pojo.rules.RuleFactory.

By specifying a custom implementation you can customize most aspects of code generation by returning custom instances of rules.

No
generateBuilders Whether to generate builder-style methods of the form withXxx(value) (that return this), alongside the standard, void-return setters. No (default false)
includeTypeInfo

Whether to include json type information; often required to support polymorphic type handling.

By default the type information is stored in the @class property, this can be overridden in the deserializationClassProperty of the schema.

No (default false)
useInnerClassBuilders Determines whether builders will be chainable setters or embedded classes when generateBuilders is used. No (default false)
includeConstructorPropertiesAnnotation Determines if constructors will be annotated with JDK-provided ConstructorProperties annotation. (Not Available on Android) No (default false)
includeGetters Whether to include getters or to omit these accessor methods and create public fields instead. No (default true)
includeSetters Whether to include setters or to omit these accessor methods and create public fields instead. No (default true)
includeAdditionalProperties Whether to allow 'additional properties' support in objects. Setting this to false will disable additional properties support, regardless of the input schema(s). No (default true)
includeDynamicAccessors Whether to include dynamic getters, setters, and builders or to omit these methods. No (default false)
includeDynamicGetters Whether to include dynamic getters or to omit these methods. No (default false)
includeDynamicSetters Whether to include dynamic setters or to omit these methods. No (default false)
includeDynamicBuilders Whether to include dynamic builders or to omit these methods. No (default false)
includeConstructors Whether to generate constructors for generated Java types No (default false)
constructorsRequiredPropertiesOnly This is a legacy configuration option used to turn on the {@link #isConstructorsIncludeAllPropertiesConstructor()} and off the {@link #isConstructorsIncludeAllPropertiesConstructor()} configuration options. It is specifically tied to the {@link #isIncludeConstructors()} property, and will do nothing if that property is not enabled No (default false)
includeRequiredPropertiesConstructor The 'constructorsIncludeRequiredPropertiesConstructor' configuration option works in collaboration with the {@link #isIncludeConstructors()} configuration option and is incompatible with {@link #isConstructorsRequiredPropertiesOnly()}, and will have no effect if {@link #isIncludeConstructors()} is not set to true. If {@link #isIncludeConstructors()} is set to true then this configuration determines whether the resulting object should include a constructor with only the required properties as parameters No (default false)
includeAllPropertiesConstructor The 'constructorsIncludeRequiredPropertiesConstructor' configuration option works in collaboration with the {@link #isIncludeConstructors()} configuration option and is incompatible with {@link #isConstructorsRequiredPropertiesOnly()}, and will have no effect if {@link #isIncludeConstructors()} is not set to true. If {@link #isIncludeConstructors()} is set to true then this configuration determines whether the resulting object should include a constructor with all listed properties as parameters. No (default true)
includeCopyConstructor The 'constructorsIncludeRequiredPropertiesConstructor' configuration option works in collaboration with the {@link #isIncludeConstructors()} configuration option and is incompatible with {@link #isConstructorsRequiredPropertiesOnly()}, and will have no effect if {@link #isIncludeConstructors()} is not set to true. If {@link #isIncludeConstructors()} is set to true then this configuration determines whether the resulting object should include a constructor the class itself as a parameter, with the expectation that all properties from the originating class will assigned to the new class. No (default false)
includeHashcodeAndEquals Whether to use include hashCode and equals methods in generated Java types. No (default true)
includeJsr303Annotations Whether to include JSR-303/349 annotations (for schema rules like minimum, maximum, etc) in generated Java types.

Schema rules and the annotation they produce:

  • maximum = @DecimalMax
  • minimum = @DecimalMin
  • minItems,maxItems = @Size
  • minLength,maxLength = @Size
  • pattern = @Pattern
  • required = @NotNull
Any Java fields which are an object or array of objects will be annotated with @Valid to support validation of an entire document tree.
No (default false)
includeJsr305Annotations Whether to include JSR-305 annotations (for defect detection) in generated Java types.

Schema rules and the annotation they produce:

  • required = @NonNull
A Java field which is required will have the @NonNull added, and @Nullable on all other fields.
No (default false)
useOptionalForGetters Whether to use Optional as return type for getters of non-required fields. No (default false)
includeToString Whether to use include a toString method in generated Java types. No (default true)
toStringExcludes A string containing fields to be excluded from toString generation. No (default "" (none))
initializeCollections Whether to initialize Set and List fields as empty collections, or leave them as null. Yes (default true)
outputEncoding The character encoding that should be used when writing the generated Java source files. No (default UTF-8)
parcelable **EXPERIMENTAL** Whether to make the generated types 'parcelable' (for Android development). No (default false)
serializable Whether to make the generated types 'serializable'. No (default false)
propertyWordDelimiters A string containing any characters that should act as word delimiters when choosing Java bean property names. No (default "- _" (hyphen, space, underscore))
removeOldOutput Whether to empty the target directory before generation occurs, to clear out all source files that have been generated previously.

Be warned, when activated this option will cause jsonschema2pojo to indiscriminately delete the entire contents of the target directory (all files and folders) before it begins generating sources.

No (default JSONSCHEMA)
skip Whether to skip type generation entirely (useful when set via a build property to allow quick disabling of this task using a command line property). No (default false)
sourceType The type of input documents that will be read

Supported values:

  • JSONSCHEMA (schema documents, containing formal rules that describe the structure of JSON data)
  • JSON (documents that represent an example of the kind of JSON data that the generated Java types will be mapped to)
  • YAMLSCHEMA (JSON schema documents, represented as YAML)
  • YAML (documents that represent an example of the kind of YAML (or JSON) data that the generated Java types will be mapped to)
No (default JSONSCHEMA)
targetPackage 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). No
useDoubleNumbers Whether to use the java type double (or Double) instead of float (or Float) when representing the JSON Schema type 'number'. No (default true)
useBigDecimals Whether to use the java type BigDecimal instead of float (or java.lang.Float) when representing the JSON Schema type 'number'. Note that this overrides useDoubleNumbers. No (default false)
useJodaDates Whether to use org.joda.time.DateTime instead of java.util.Date when adding date-time type fields to generated Java types. No (default false)
useJodaLocalDates Whether to use org.joda.time.LocalDate instead of java.lang.String when adding string fields with format date to generated Java types. No (default false)
useJodaLocalTimes Whether to use org.joda.time.LocalTime instead of java.lang.String when adding string fields with format time to generated Java types. No (default false)
useLongIntegers Whether to use the java type long (or Long) instead of int (or Integer) when representing the JSON Schema type 'integer'. No (default false)
useBigIntegers Whether to use the java type BigInteger instead of int (or java.lang.Integer) when representing the JSON Schema type 'integer'. Note that this overrides useLongIntegers. No (default false)
usePrimitives Whether to use primitives (long, double, boolean) instead of wrapper types where possible when generating bean properties (has the side-effect of making those. No (default false)
targetVersion The target version for generated source files. No (default 1.6)
dateTimeType The java type to use instead of java.util.Date when adding date-time type fields to generated Java types.
  • org.joda.time.LocalDateTime (Joda)
  • java.time.LocalDateTime (JSR310)
No
dateType The java type to use instead of java.lang.String when adding string fields with format date to generated Java types.
  • org.joda.time.LocalDate (Joda)
  • java.time.LocalDate (JSR310)
No
timeType The java type to use instead of java.lang.String when adding string fields with format time to generated Java types.
  • org.joda.time.LocalTime (Joda)
  • java.time.LocalTime (JSR310)
No
formatDates Whether the fields of type `date` are formatted during serialization with a default pattern of yyyy-MM-dd'T'HH:mm:ss.SSSZ. No (default false)
formatTimes Whether the fields of type `time` are formatted during serialization with a default pattern of HH:mm:ss.SSS. No (default false)
formatDateTimes Whether the fields of type `date` are formatted during serialization with a default pattern of yyyy-MM-dd'T'HH:mm:ss.SSSZ. No (default false)
customDatePattern A custom pattern to use when formatting date fields during serialization. Requires support from your JSON binding library. No (default none)
customTimePattern A custom pattern to use when formatting time fields during serialization. Requires support from your JSON binding library. No (default none)
customDateTimePattern A custom pattern to use when formatting date fields during serialization. Requires support from your JSON binding library. No (default none)
refFragmentPathDelimiters A string containing any characters that should act as path delimiters when resolving $ref fragments. By default, #, / and . are used in an attempt to support JSON Pointer and JSON Path. No (default #/.)
sourceSortOrder The sort order to be applied to the source files when being processed, by default the OS can influence the ordering.
  • OS (Let the OS influence the order that the source files are processed.)
  • FILES_FIRST (Case sensitive sort, visit the files first. The source files are processed in a breadth first sort order.)
  • SUBDIRS_FIRST (Case sensitive sort, visit the sub-directories before the files. The source files are processed in a depth first sort order.)
No (default OS)
formatTypeMapping A mapping from format identifier (e.g. 'uri') to Java type (e.g. 'java.net.URI'): >format<:>fully.qualified.Type<. None (default '' (none))
includeGeneratedAnnotation Include @javax.annotation.Generated annotation to generated types No (default true)
useJakartaValidation Whether to use annotations from jakarta.validation package instead of javax.validation package when adding JSR-303 annotations to generated Java types.
This configuration option works in collaboration with the includeJsr303Annotations configuration option and will have no effect if latter is set to false
No (default false)

Examples

<taskdef name="jsonschema2pojo" classname="org.jsonschema2pojo.ant.Jsonschema2PojoTask">
    <classpath> <!-- classpath only required if jars have *NOT* been added to $ANT_HOME/lib -->
        <fileset dir="my-downloaded-libs">
            <include name="**/*.jar" />
        </fileset>
    </classpath>
</taskdef>

<target name="generate">
    <jsonschema2pojo source="address.json"
                     targetDirectory="build/generated-types"
                     targetPackage="com.example"/>
</target>
    

The above uses the taskdef task to make the jsonschema2pojo task available. The generate target invokes the jsonschema2pojo task to generate java classes based on an input schema called address.json.