Convert/ Serialize Object /POJO to /from JSON String in java (Gson & example)

  • Given a user defined object, we would like to convert Object( or POJO) to JSON and vice versa.
  • We will use the Google gson library to serialize POJO to JSON and deserialize JSON to POJO.
  • We will create Person class and we will perform the following operations with Person class
    • Convert Person Object to JSON String.
    • Convert JSON String to person object

GSON Maven dependency:

<dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.5</version>
</dependency>

Program – convert Object to /from JSON String in java (GSON & example)

1.) Person Class:

  • Given a Person class or POJO, we would like to serialize or convert object to JSON String.
  • Person class is having data members like firstName, lastName, age etc.
  • We have overloaded toString method, to display Person information
package org.learn.gson;

public class Person {
 public String firstName;
 public String lastName;
 public int age;
 public String contact;

 public Person(String firstName, String lastName, int age, String contact) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.contact = contact;
 }

 public String toString() {
  return "[" + firstName + " " + lastName + " " + age + " " + contact + "]";
 }
}

2) JSONObjectConverter Class:

JSONObjectConverter is responsible for performing following operations.

  1. Convert Person Object to JSON String.
    • Serialization of Object to JSON String.
  2. Convert JSON String to person object.
    • Deserialization of JSON String to Person Object.
package org.learn.gson;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class JSONObjectConverter {
 public static void main(String[] args) {
  Gson objGson = new GsonBuilder().setPrettyPrinting().create();
  Person objPerson = new Person("Mike", "harvey", 34, "001894536");
  // Convert Person object to json
  String json = objGson.toJson(objPerson);
  System.out.println("1. Convert Person object to Json");
  System.out.println(json);

  // Convert to json to person object
  Type listType = new TypeToken() {
  }.getType();
  System.out.println("2. Convert JSON to person object");
  Person objFromJson = objGson.fromJson(json, listType);
  System.out.println(objFromJson);
 }
}

Download – Serializae & Deserialize or convert object to/from JSON (GSON)

Output – convert object to/from JSON in java (GSON & example)

1. Convert Person object to Json
{
  "firstName": "Mike",
  "lastName": "harvey",
  "age": 34,
  "contact": "001894536"
}
2. Convert JSON to person object
[Mike harvey 34 001894536]
Scroll to Top