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)
  • JACKSON1 (apply annotations from the Jackson 1.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)
inclusionLevel The level of inclusion to be set for generated java types (to control level of inclusion in case of Jackson1 or Jackson2 serializator). 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. Valid for both versions of Jackson.
  • 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. Valid only for jackson2, for Jackson1 NON_NUL is used.
  • NON_DEFAULT Meaning of this setting depends on context: whether annotation is specified for POJO type (class), or not Valid for both versions of Jackson.
  • NON_EMPTY Value that indicates that only properties with null value, or what is considered empty, are not to be included. Valid for both versions of Jackson.
  • NON_NULL Value that indicates that only properties with non-null values are to be included. Valid for both versions of Jackson.
  • USE_DEFAULTS Pseudo-value used to indicate that the higher-level defaults make sense, to avoid overriding inclusion value. Valid only for jackson2, for Jackson1 NON_NUL is used.
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)
includeAccessors Whether to include getters/setters or to omit these accessor methods and create public fields instead. No (default true)
includeGetters Whether to include getters or to omit these accessor methods and create public fields instead. No (default false)
includeSetters Whether to include setters or to omit these accessor methods and create public fields instead. No (default false)
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 Whether generated constructors should have parameters for all properties, or only required ones. 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)
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)
No (default JSONSCHEMA)
targetLanguage The type of code that will be generated.

Supported values:

  • JAVA
  • SCALA
No
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
useCommonsLang3 Whether to use commons-lang 3.x imports instead of commons-lang 2.x imports when adding equals, hashCode and toString methods. No (default false)
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)

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.