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 (67 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>
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.
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
6)Now run the code. Once you run will see following kind of output
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);
3)Now run the code. Once you run will see following kind of output