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.
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.
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.
So just by following few simple steps we can save a lot of time for us. That’s all for this article.