Convert JSON to Java POJO

Here’s a brief tutorial to covert JSON to JAVA POJOs (code) or in other words, generating Java POJOs from a given JSON definition. This could prove really handy in the Microservices world, where you may have to work with and generate a lot of request response objects whether it be internal or third party API related. We are making use of the Jackson library for the purpose.

The entire working code listed below is available on this github repo.

Below snippets depict the intended input and output from this:

Note: For the purpose of brevity, we are not putting the complete output here. (it’s provided at the bottom of this page)

gets converted to Java code:

To enable our project with this capability we start by making a sample maven project.
Then add the dependencies below in our pom.xml:

The notable tags here are:

and

As the names suggest, the sourceDirectory contains path to source Json file(s), while the targetPackage is the name of the package with which the classes would be generated.
The outputDirectory is the folder where generated java file would be saved.

As an example, save the above shown JSON schema as test.json in the specified sourceDirectory.
now just do a maven install on the project:

and you should get the below Java class in the ${project.build.directory}/generated-sources/com/coddicted/gen folder:

Rate this post

Leave a Reply