Learn to use Google GSON library to serialize Java Objects into their JSON string and to deserialize a JSON string to an equivalent Java object. GSON provides simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa.
1. Dependency
Maven dependency. Visit the maven repository for the latest version.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
Gradle dependency.
dependencies {
implementation 'com.google.code.gson:gson:2.8.9'
}
2. Serialization – Write JSON using Gson
Serialization in the context of Gson means converting a Java object to its JSON representation.
In order to do the serialization, we need to create the Gson
object, which handles the conversion. Next, we need to call the function toJson() and pass the User
object.
import java.time.LocalDate;
import java.time.Month;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.howtodoinjava.demo.model.Department;
import com.howtodoinjava.demo.model.User;
public class SerializationExample {
public static void main(final String[] args) {
User user = new User(1L, "lokesh", "gupta",
LocalDate.of(1999, Month.JANUARY, 1), new Department(2, "IT", true));
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
String jsonString = gson.toJson(user);
System.out.println(jsonString);
}
}
Program output.
{
"id": 1,
"firstName": "lokesh",
"lastName": "gupta",
"dateOfbirth": "1999-01-01",
"department": {
"id": 2,
"name": "IT",
"active": true
}
}
3. Deserialization – Read JSON using Gson
Deserialization in the context of Gson means converting a JSON string to an equivalent Java object.
In order to do the deserialization, we need a Gson
object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished.
import java.time.LocalDate;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.howtodoinjava.demo.model.User;
public class DeserializationExample {
public static void main(final String[] args) {
String jsonString = """
{
"id": 1,
"firstName": "lokesh",
"lastName": "gupta",
"dateOfbirth": "1999-01-01",
"department": {
"id": 2,
"name": "IT",
"active": true
}
}""";
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
.create();
User user = gson.fromJson(jsonString, User.class);
System.out.println(user);
}
}
Program output.
User(id=1, firstName=lokesh, lastName=gupta, dateOfbirth=1999-01-01,
department=Department(id=2, name=IT, active=true))
Happy Learning !!
Leave a Reply