HomeJavaHow to Generate Plain Old Java Objects from JSON or JSON-Schema

How to Generate Plain Old Java Objects from JSON or JSON-Schema

Convert JSON-Schema to Java POJO

One of our previous journals showcases how you can easily convert JSON data to Java POJO. In case you have missed that journal then we would suggest you to have a look at “Easy way to convert JSON to Java POJO”. In this journal, we will be taking the journey of converting JSON-Schema to Java POJO. First though, we need a valid JSON Schema document. If you don’t have one to hand, you can use the Address example found here:

http://www.json-schema.org/address

There are currently Six ways to achieving this target.

  • Online Version: You can use this online utility JSONSchema2Java. Copy/Paste your valid JSON-Schema in the box provided and change the settings as per your requirements. Once you are done with the settings click on the Preview button to have a look at how your POJO will look like. After satisfaction of the preview, you can go ahead and download the POJO for use in your projects.
  • as a maven plugin using jsonschema2pojo-maven-plugin
  • via the command line using jsonschema2pojo-cli
  • as an ant task using jsonschema2pojo-ant
  • as a gradle plugin using gradle-jsonschema2pojo-plugin
  • directly from your code (embedded) using jsonschema2pojo-core

#Maven Plugin

The Maven plugin provides a generate goal that attaches to the generate-sources phase by default.

For a quick example, place the address schema into src/main/resources/schema and edit your pom.xml to include the following in the <build> section:

<plugins>
  <plugin>
    <groupId>org.jsonschema2pojo</groupId> 
    <artifactId>jsonschema2pojo-maven-plugin</artifactId> 
    <version>0.4.37</version> 
    <configuration> 
      <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory> 
      <targetPackage>com.example.types</targetPackage> 
    </configuration> 
    <executions> 
      <execution> 
        <goals> 
          <goal>generate</goal> 
        </goals> 
      </execution> 
    </executions> 
  </plugin>
</plugins>

The generated types target Java 6, so if you haven’t already then you’ll need to set your source/target version to 1.6 or higher by adding the following to the <build> section of your pom:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>

At present the generated types depend on Commons Lang for equalshashCode and toString. Some schema constructs will also cause parser hints in the form of Jackson annotations. To compile your generated types, you’ll need to make the necessary additions to your <dependencies>:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.4</version>
</dependency>

Finally, on running mvn package you’ll see a newly generated file target/java-gen/com/example/types/Address.java. You should also notice that the com.example.types.Address class has been compiled and included in your project bundle.

#Command Line

If you’re using OSX and brew, try brew install jsonschema2pojo. If not, then start by downloading the latest release from:

https://github.com/joelittlejohn/jsonschema2pojo/releases

Extract the release, you should see some jsonschema2pojo jar files, a lib folder and two scripts (bash and bat).

We’ll use the example address schema to generate our types. Download the address schema, and invoke jsonschema2pojo like:

jsonschema2pojo --source address --target java-gen

For the full usage details, use the --help option:

jsonschema2pojo --help

#Ant Task

To invoke the jsonschema2pojo Ant task, you’ll need to download the latest task itself, and some dependencies:

Either place the downloaded jars in $ANT_HOME/lib, or place them in a folder of your choosing.

Now simply add a the taskdef task to your build.xml to make the jsonschema2pojo task available. Once the taskdef has been added, you can invoke the task. E.g.

<?xml version="1.0" encoding="UTF-8"?>
<project name="myproject" default="generate">

    <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>

</project>

#Within your Java project (embedded)

To use the jsonschema2pojo API directly from a Java application you’ll need to add the jsonschema2pojo-core jar to your build path. You can obtain this by downloading the latest jar or by adding the following dependency to your Maven project:

<dependency>
    <groupId>org.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-core</artifactId>
    <version>0.4.37</version>
</dependency>

If you’re not using Maven, you’ll need to gather some further dependencies:

Now you’re ready to use the jsonschema2pojo schema mapper in your code:

JCodeModel codeModel = new JCodeModel();

URL source = new URL("file:///path/to/my/schema.json");

GenerationConfig config = new DefaultGenerationConfig() {
	@Override
	public boolean isGenerateBuilders() { // set config option by overriding method
		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(new File("output"));
RELATED ARTICLES

Most Popular