Convert java object to json and convert json to java object

What you will learn here about java

  • Convert java object to json
  • Convert json to java object

Here you will learn how to convert Java object to json using Gson and How to convert json to java Object using Gson.

Please click on below link to download sample project.
Download sample maven project to convert java object to json and json to java object (20 downloads)

Convert java object to json

Please follow the following steps to know the how to convert Java object to json
1)First create a Maven project

2)Add below gson dependency in pom.xml which is shown below

  <dependencies>
	  <dependency>
	       <groupId>com.google.code.gson</groupId>
	       <artifactId>gson</artifactId>
	       <version>2.6.2</version>
	   </dependency>	
  </dependencies>

gson pom.xml dependency

3)Now create a class whose object you want to convert into json. Below I have created Employee class with variables, its constructor and getter and setter methods which is shown below.
Convert java object to json

4)Now create a new class for main method

5)Now Use toJson() method of Gson to convert Java object to json which is shown below

How to convert Java object to json using Gson

6)Now run the code. Once you run will see following kind of output
Java object to json conversion

Convert json to java object

Please follow the following steps to know the how to Convert json to java object
1)Assuming you have followed above steps

2)Now please add following line to converts json to java object which is shown below

Employee user = gson.fromJson(gson.toJson(employee), Employee.class);

Convert json to java object

3)Now run the code. Once you run will see following kind of output
How to Convert json to java object

You may also like...