In this post, we will learn to convert JSON string to java object using GSON
We can convert json string to java object in multiple ways. Among those Gson conversion is familiar and quite easy too.
We need below dependency to convert JSON string to java object
Dependency
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
In this example we are going to convert below json object to java object
{
"studentId": "001",
"studentName": "Rajesh",
"schoolName": "BeginnerBug",
"department": "Java"
}
Syntax
Student student = gson.fromJson(jsonString, Student.class);
Example
import com.beginnersbug.example.model.Student;
import com.google.gson.Gson;
public class ConvertJsonToJava {
public static void main(String[] args) {
try {
String jsonString = "{\"studentId\":\"001\",\"studentName\":\"Rajesh\",\"schoolName\":\"BeginnerBug\",\"department\":\"Java\"}";
Gson gson = new Gson();
Student student = gson.fromJson(jsonString, Student.class);
System.out.println(student.getStudentName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Student.java
public class Student {
private String studentId;
private String studentName;
private String schoolName;
private String department;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
Output
Rajesh
Conclusion
From the above code snippet we can easily convert json string to java object
Reference
Json Viewer http://jsonviewer.stack.hu/
Convert string to java object http://www.jsonschema2pojo.org/
Github
Related Articles
read value from application.properties spring boot