In order to convert a Java JSON String to a Java Object and vice-versa, we can make use of the Google Gson dependency,
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Add Gson dependency in Maven POM.xml
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
Add Gson dependency in Gradle build.gradle
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.3.1'
Example: Java JSON String to a Java Object
Student.json[
{
"studentId": 1,
"studentName": "Mike",
"studentAddress": "Paris",
"studentAge": 19,
"studentMarks": {
"English": 87,
"Chemistry": 72,
"Math": 75,
"Physics": 67
}
},
{
"studentId": 2,
"studentName": "Alex",
"studentAddress": "London",
"studentAge": 18,
"studentMarks": {
"English": 71,
"Chemistry": 98,
"Math": 89,
"Physics": 76
}
}
]
Students.java
import java.util.HashMap;
public class Student {
public Student(int studentId, String studentName, String studentAddress, int studentAge, HashMap<String, Integer> studentMarks) {
this.studentId = studentId;
this.studentName = studentName;
this.studentAddress = studentAddress;
this.studentAge = studentAge;
this.studentMarks = studentMarks;
}
private int studentId;
private String studentName;
private String studentAddress;
private int studentAge;
private HashMap<String,Integer> studentMarks;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(String studentAddress) {
this.studentAddress = studentAddress;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public HashMap<String, Integer> getStudentMarks() {
return studentMarks;
}
public void setStudentMarks(HashMap<String, Integer> studentMarks) {
this.studentMarks = studentMarks;
}
}
JsonToGsonExample.java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
public class JsonToGsonExample {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"studentId\": 1,\n" +
" \"studentName\": \"Mike\",\n" +
" \"studentAddress\": \"Paris\",\n" +
" \"studentAge\": 19,\n" +
" \"studentMarks\": {\n" +
" \"English\": 87,\n" +
" \"Chemistry\": 72,\n" +
" \"Math\": 75,\n" +
" \"Physics\": 67\n" +
" }\n" +
"}";
String jsonStringList ="[\n" +
" {\n" +
" \"studentId\": 1,\n" +
" \"studentName\": \"Mike\",\n" +
" \"studentAddress\": \"Paris\",\n" +
" \"studentAge\": 19,\n" +
" \"studentMarks\": {\n" +
" \"English\": 87,\n" +
" \"Chemistry\": 72,\n" +
" \"Math\": 75,\n" +
" \"Physics\": 67\n" +
" }\n" +
" },\n" +
" {\n" +
" \"studentId\": 2,\n" +
" \"studentName\": \"Alex\",\n" +
" \"studentAddress\": \"London\",\n" +
" \"studentAge\": 18,\n" +
" \"studentMarks\": {\n" +
" \"English\": 71,\n" +
" \"Chemistry\": 98,\n" +
" \"Math\": 89,\n" +
" \"Physics\": 76\n" +
" }\n" +
" }\n" +
"]";
Gson gson = new Gson();
//Example with just one Json Object
Student student = gson.fromJson(jsonString,Student.class);
System.out.println(student.getStudentName());
System.out.println(student.getStudentAddress());
//Example with a Student List
ArrayList<Student> studentsList = new ArrayList<>();
studentsList = gson.fromJson(jsonStringList, new TypeToken<ArrayList<Student>>(){}.getType());
System.out.println(studentsList.get(0).getStudentName());
System.out.println(studentsList.get(1).getStudentName());
}
}
Output:
Mike
Paris
Mike
Alex
Example: Gson Java Object to JSON String
GsonToJsonExample.javaimport com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GsonToJsonExample {
public static void main(String[] args) {
HashMap<String,Integer> mikeMarks = new HashMap<>();
mikeMarks.put("English",87);
mikeMarks.put("Math",75);
mikeMarks.put("Physics",67);
mikeMarks.put("Chemistry",72);
HashMap<String,Integer> alexMarks = new HashMap<>();
alexMarks.put("English",71);
alexMarks.put("Math",89);
alexMarks.put("Physics",76);
alexMarks.put("Chemistry",98);
Student studentMike = new Student(1,"Mike","Paris",19,mikeMarks);
Student studentAlex = new Student(2,"Alex","London",18,alexMarks);
List<Student> studentList = new ArrayList<>();
studentList.add(studentMike);
studentList.add(studentAlex);
Gson gson = new Gson();
System.out.println(gson.toJson(studentList));
}
}
Output:
More Posts related to Java,
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
More Posts:
- Special character & not working with SharePoint REST API - SharePoint
- [fix] Execution failed for task :core:compileJava - Could not find tools.jar - Gradle
- [Fix] Java - Exception in thread main java.lang.IllegalThreadStateException - Java
- [Fix] Docker Run unknown shorthand flag: 'r' in -rm - Docker
- How to Set JAVA_HOME PATH to Mac .zshrc profile file - Java
- How to create a Java Project as a Git Repository with IntelliJ - Java
- Open Large File in Notepad++ (Fix: File is too big to be opened by Notepad++) - NotepadPlusPlus
- Right Align Text in Bootstrap framework - Bootstrap