Convert JSON to Object in Java

In this example, We will show you about, How to convert JSON to object in java. The program has been tested and output has been shared in the same post.

Project Structure

Convert JSON to Object in Java

Input JSON File

{"employee":{
"empId":101,
"empName":"Dinesh Krishnan",
"empAge":20,
"empQualification":"MS",
"empSalary":1000
}}

Simple POJO Class

package com.dineshkrish.json;
public class Employee {
private int empId;
private String empName;
private int empAge;
private String empQualification;
private double empSalary;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpAge() {
return empAge;
}
public void setEmpAge(int empAge) {
this.empAge = empAge;
}
public String getEmpQualification() {
return empQualification;
}
public void setEmpQualification(String empQualification) {
this.empQualification = empQualification;
}
public double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
}

Converting JSON to Object

package com.dineshkrish.json;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.Gson;
/**
* 
* @author Dinesh Krishnan
*
*/
public class ConvertJSONToObject {
public static void main(String[] args) {
Employee employee = null;
Gson gson = new Gson();
File jsonFile = new File("input/data.json");
try {
FileReader reader = new FileReader(jsonFile);
employee = gson.fromJson(reader, Employee.class);
System.out.println("JSON File Converted to Object");
System.out.println("--------------------------");
System.out.println("ID : "+employee.getEmpId());
System.out.println("Name : "+employee.getEmpName());
System.out.println("Age : "+employee.getEmpAge());
System.out.println("Qualification : "+employee.getEmpQualification());
System.out.println("Salary : "+employee.getEmpSalary());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Download Source Code

You can able to download the source code from here

Output

JSON File Converted to Object
————————–
ID : 101
Name : Dinesh Krishnan
Age : 20
Qualification : MS
Salary : 1000.0

References

1. Java File Class
2. Java FileReader Class
3. Gson Class Documentation
4. fromJson(Reader json, Class classOfT) method

No responses yet

Leave a Reply

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