How to Create JAVA objects from JSON Easily?

Why do we need to parse JSONs? We need to parse JSONs to get the values from the fields. For a small JSON payload it is fine but for a large one it is a way boring task besides it consumes a lot of our time to generate a lot of JAVA classes. So to get rid of this problem we can make use of a maven dependency “jsonschema2pojo-maven-plugin” which automates creation of java classes for any JSON. So follow the below steps to get started.

Step 1: Clone the project from the below GitHub repo. You can also download the zip from GitHub, extract it and then import it in the IDE you will be using. For this demo I will be using STS.

https://github.com/chargeahead/JsonToJavaObjects/tree/master/src/main/java/com/demo/Json

Step 2: Once the project is imported into STS expand the project structure open the schema folder which is shown below in the path: src->main->resources->schema and replace the content of “demo.json” file with your JSON and save it. In addition you can also do a maven update to download all the dependencies.

Paste your JSON in the demo.json file
Sample Employee Json in the demo.json file

Step 3 : Build the above maven project. To build the project right click on your project and select Run As->Maven Build. If it is asking to specify the maven goal the you have to give “generate-sources” as the maven goal.

Select Maven Build From Run As

Step 4: Once the build is successful refresh the project by pressing F5 or right click on the project and select Refresh. Once refreshed go to the path inside target as shown in the picture. You can see there are 2 classes generated. One is the main class (Demo.java) which is the main class and another class Contact Details (Contactdetails.java) which is the composite class.

Step 5: Verify if the classes contains all fields and methods. You can check the datatype of the fields and methods as well.

Demo.java
Contactdetails.java

So just by following few simple steps we can save a lot of time for us. That’s all for this article.

Related Posts

git good practice

Be a Better Developer with These Git Good Practices

Discover the path to becoming a more proficient developer with these essential Git best practices. Learn the art of crafting meaningful commit messages, and adopting a strategic branching approach such as Git Flow.

Top-Spring-Boot-Interview-Questions-Part-1

Top Spring Boot Interview Questions – Part 1

1. What is Spring Boot, and why is it used? Spring Boot is an opensource framework that simplifies the development of Java applications. It’s used to quickly…

Automatically-format-your-code-on-git-commit-using-prettier-husky-eslint

How to auto format & clean code on commit?

If you are working a project with more than 2 developers, you might note different formatting code create different kinds of issue like merge conflicts, code…

Leave a Reply

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