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Ā equals,Ā hashCodeĀ 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