How to convert json string to java object using Gson APIs?
This page shows how to convert json string to java object using Google gson API.
Note: Refer How to convert java object to json string using Gson APIs? page for dependent libraries.
Create a simple Employee pojo. We will map json string to this pojo.
package com.java2novice.json.gson;
public class Employee {
private int empId;
private String name;
private String designation;
private String department;
private int salary;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
|
Input Json String: |
{
"empId": 1017,
"name": "Nagesh Y",
"designation": "Manager",
"department": "Java2Novice",
"salary": 30000
}
|
Finally here is the example to convert json string to java object:
package com.java2novice.json.gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.Gson;
public class JsonToObjectEx {
public static void main(String a[]){
BufferedReader br = null;
Gson gsonObj = new Gson();
try {
br = new BufferedReader(new FileReader("/Users/ngootooru/jsonInput.txt"));
// convert json string to object
Employee emp = gsonObj.fromJson(br, Employee.class);
System.out.println("Emp Name: "+emp.getName());
System.out.println("Emp Id: "+emp.getEmpId());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
|