How to convert JSON schema to Java classes using maven plugin - Little Big Extra Skip to main content

How to convert JSON schema to Java classes using maven plugin

Convert JSON schema to Java classes using maven plugin

Introduction

We often need to convert JSON schema’s to Java classes, there is a jsonschema2pojo-maven-plugin which helps in generating POJO(plain old java objects) from JSON or JSON schema.

To use it all we need is add this plugin, update dependencies and run mvn generate

Add jsonschema2pojo-maven-plugin in POM.XML

Add this plugin to your POM.XML under plugin section

Add Maven dependencies

The generated types depend on Commons Lang library for equals, hashCode and toString. Also, you need to add Jackson-databind which contains the data-binding functionality and tree-model for Jackson Data Processor, this jar has a transitive dependency on jackson-core and jackson-annotations so they will be downloaded automatically.

 

Run the Maven Goal

You can run mvn generate-sources goal to generate the java classes. All files will be added in the target/java-gen folder by default
If you need it to be generated in another folder you can make use of ${basedir}/src/main/gen
however I have noticed that specifying any other folder doesn’t add that folder automatically as source folder in eclipse, so you might see some compilation errors.

Make sure that generated folder is added as a source folder in your IDE (Properties ->Java build Path -> Add source folder in eclipse).

Generating classes from JSON and not from schema

If you want to generate Java classes from JSON rather than JSON schema add

inside the configuration tag as default source type is JSON Schema.

Related Posts

5 thoughts to “How to convert JSON schema to Java classes using maven plugin”

    1. I pasted the entire snippet “sourceType” json “sourceType”, but apparently this comment plugin is quite strict on XSS and strips out anything with brackets 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami