Converting JSON to and From Java Object using GSON

Converting JSON to and From Java Object using GSON

In this tutorial we will discuss how to Convert JSON to and From Java Object using GSON developed by Google. We will discuss various different mechanisms in order to serialize and deserialize JSON to/from Java Objects.

What’s Covered

  1. Google GSON Library
  2. Converting Java Object to JSON using GSON
  3. Converting Java Object to JSON using PrettyPrint in GSON
  4. Converting JSON to Java Object in GSON
  5. Converting JSON to Java Object using Reader in GSON
  6. Read JSON from a FileInputStream in GSON
  7. Read JSON from InputStreamReader in GSON
  8. Read JSON from a URL in GSON
  9. Write Object to FileOutputStream in GSON
  10. Reviewing our Java Object Customer.class

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 1.6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
  • Google GSON 2.2.2 Java library that can be used to convert Java Objects into their JSON representation

Required Libraries

In my example, I have copied the required library to the lib folder.

gson-2.2.2.jar

You will then configure your libraries in the Libraries tab on Java Build Path Dialog Screen (shown below).

gson_lib_setup

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

gson_proj_struct

Google GSON Library

Google GSON provides the functionality for performing the actual conversions between Java Objects and JSON equivalents. The GSON package contains many classes like GsonBuilder and GSON. Using these classes we can read and write JSON from String, File, Streams, URLs, etc.

It performs the serialization (process of writing or converting the object to JSON) using the object’s “getter” methods. It also performs the opposite, using deserialization (process of writing or converting the JSON back to a Java Object) using the object’s “setter” methods.

Converting Java Object to JSON using GSON

In order to convert Java Objects (POJOs) to JSON we use one several methods available to us.

  • toJson() performs the serialization, that is, converts a Java Object to its JSON string
  • fromJson() performs the deserialization of the JSON string and builds a Java Object from its representation

In the following example, you will notice that I am using toJson() method which will serialize the Java Object into the JSON String equivalent. We pass our Java object (POJO), in our case, the customer instance, we want to serialize as the parameter to this method.

// Java Object to JSON String
Customer customer1 = new Customer("001", "Amaury", 
    "Valdes", "100 Main Street", "Newark", 
    "New Jersey", "07044", "908-321-8080",
    "amaury.valdes@mail.com", "avaldes.com");

Gson gson = new Gson();
String json = gson.toJson(customer1, Customer.class);
System.out.println(json);

Output of Converting Java Object to JSON

{"customerId":"001","firstName":"Amaury","lastName":"Valdes",
"address":"100 Main Street","city":"Newark","state":"New Jersey",
"zipCode":"07044","phoneNumber":"908-321-8080","emailAddress":
"amaury.valdes@mail.com","companyName":"avaldes.com"}

Converting Java Object to JSON using setPrettyPrinting in GSON

In this example, we use GsonBuilder() class and use its setPrettyPrinting() method to format the JSON output with indentation for a nicer JSON presentation.

// Java Object to JSON String
Customer customer1 = new Customer("001", "Amaury", 
    "Valdes", "100 Main Street", "Newark", 
    "New Jersey", "07044", "908-321-8080",
    "amaury.valdes@mail.com", "avaldes.com");

Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
json = prettyGson.toJson(customer1);
System.out.println(json);

Output of Converting Java Object to JSON using PrettyPrinting

{
  "customerId": "001",
  "firstName": "Amaury",
  "lastName": "Valdes",
  "address": "100 Main Street",
  "city": "Newark",
  "state": "New Jersey",
  "zipCode": "07044",
  "phoneNumber": "908-321-8080",
  "emailAddress": "amaury.valdes@mail.com",
  "companyName": "avaldes.com"
}

Converting JSON to Java Object in GSON

Google GSON makes converting a JSON String very straight-forward and simple. We use the fromJson method and pass the JSON string as the first parameter and use the class as the second parameter in the method. This process will deserialize the JSON back to its Java Object equivalent.

// Read JSON to Object
json = "{\"customerId\": \"002\", "
    + "\"firstName\":\"Jennifer\", "
    + "\"lastName\":\"Wilson\","
    + "\"address\":\"89 Maple Street\","
    + "\"companyName\":\"amazon.com\","
    + "\"city\":\"Plainsboro\","
    + "\"state\":\"New Jersey\","
    + "\"zipCode\":\"08873\","
    + "\"phoneNumber\":\"888-829-2828\","
    + "\"emailAddress\":\"jen.wilson@amazon.com\""
    + "}";
Customer cust2 = gson.fromJson(json, Customer.class);
System.out.println(cust2);

Output of JSON to Java Object

Customer [customerId=002, firstName=Jennifer, 
lastName=Wilson, address=89 Maple Street, city=Plainsboro, 
state=New Jersey, zipCode=08873, phoneNumber=888-829-2828, 
emailAddress=jen.wilson@amazon.com, companyName=amazon.com]

Converting JSON to Java Object using Reader in GSON

In this next example, we show you how GSON can perform the deserialization from JSON to Java objects using a Reader, which is the abstract class for all of the Readers in the Java IO API. Subclasses include BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, and StringReader.

In this example, we are using the StringReader which reads a character stream where the source is a String.

// Read JSON from Reader
json = "{\"customerId\": \"004\", "
    + "\"firstName\":\"Dennis\", "
    + "\"lastName\":\"Hunter\","
    + "\"address\":\"15 Terhune Road\","
    + "\"city\":\"Clover\","
    + "\"state\":\"South Carolina\","
    + "\"zipCode\":\"29710\","
    + "\"companyName\":\"Arnold Furniture, Co.\","
    + "\"phoneNumber\":\"888-829-2828\","
    + "\"emailAddress\":\"dennis@arnold.com\""
    + "}";

reader = new StringReader(json);
Customer cust4 = gson.fromJson(reader, Customer.class);
System.out.println(cust4);

Output of Converting JSON to Java Object using Reader in GSON

Customer [customerId=004, firstName=Dennis, lastName=Hunter, 
address=15 Terhune Road, city=Clover, state=South Carolina, 
zipCode=29710, phoneNumber=888-829-2828, 
emailAddress=dennis@arnold.com, companyName=Arnold Furniture, Co.]

Read JSON from File using FileInputStream

In this example we will be using FileInputStream class to read a JSON text file from the file system. GSON’s fromJson method supports JsonElement, Reader, and String.

Sample File (customer3.json)

{
  "customerId": "003",
  "firstName": "Marisa",
  "lastName": "Smith",
  "address": "300 Mount Laurel Avenue",
  "city": "Middletown",
  "state": "New Jersey",
  "zipCode": "07055",
  "phoneNumber": "800-555-1212",
  "emailAddress": "marisa.smith@gmail.com",
  "companyName": "Google Services"
}
// Read JSON from FileInputStream
Reader reader = null;
FileInputStream in;
try {
  in = new FileInputStream("resources/customer3.json");
  try {
    reader = new InputStreamReader(in, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
}
Customer cust3 = gson.fromJson(reader, Customer.class);
System.out.println(cust3);

Output of Reading JSON from File

Customer [customerId=003, firstName=Marisa, lastName=Smith, 
address=300 Mount Laurel Avenue, city=Middletown, 
state=New Jersey, zipCode=07055, phoneNumber=800-555-1212, 
emailAddress=marisa.smith@gmail.com, companyName=Google Services]

Read JSON from InputStreamReader in GSON

An InputStreamReader allows us to read characters from files; It reads bytes and decodes them into characters using a specified charset. The InputStreamReader may read one or more bytes from the underlying byte-input stream, usually an InputStream.

For this example, we will be using the same file that we used in our previous example. But as you can see, using InputStreamReader is quite a simple process.

Sample File (customer5.json)

{
  "customerId": "005",
  "firstName": "Robert",
  "lastName": "Smith",
  "address": "123 Passaic Street",
  "city": "Passaic",
  "state": "New Jersey",
  "zipCode": "07055",
  "phoneNumber": "800-555-1212",
  "emailAddress": "robert.smith@gmail.com",
  "companyName": "Google Services"
}
// Read JSON from InputStream (requires Reader)
InputStream inStream = null;
InputStreamReader inReader = null;
try {
  inStream = new FileInputStream(
      "resources/customer5.json");
} catch (FileNotFoundException e2) {
  e2.printStackTrace();
}
try {
  inReader = new InputStreamReader(inStream, "UTF-8");
} catch (UnsupportedEncodingException e2) {
  e2.printStackTrace();
}
Customer cust5 = gson.fromJson(inReader, Customer.class);
System.out.println(cust5);

Output of Reading JSON from InputStreamReader

Customer [customerId=005, firstName=Robert, lastName=Smith, 
address=123 Passaic Street, city=Passaic, state=New Jersey, 
zipCode=07055, phoneNumber=800-555-1212, 
emailAddress=robert.smith@gmail.com, companyName=Google Services]

Read JSON from a URL in GSON

GSON requires us to wrap the URL class inside of InputStreamReader as the fromJson only supports three classes on which Reader is one of them.

// Read JSON from URL (requires Reader)
try {
  inReader = new InputStreamReader(
      new URL("https://avaldes.com/data/customer6.json")
        .openStream());
  Customer cust6 = gson.fromJson(inReader, Customer.class);
  System.out.println(cust6);
} catch (MalformedURLException e1) {
  e1.printStackTrace();
} catch (IOException e1) {
  e1.printStackTrace();
}

Output of Read JSON from a URL

Customer [customerId=006, firstName=Mark, lastName=Davidson, 
address=829 Florence Street, city=Reading, state=Pennsylvania, 
zipCode=19606, phoneNumber=800-782-2222, 
emailAddress=mark.davidson@aramark.com, companyName=Aramark]

Write Object to FileOutputStream in GSON

// Write Object to FileOutputStream
JsonWriter writer = null;
try {
  Customer customer7 = new Customer("007", "Andrew", 
      "Shaw", "283 Licoln Blvd", "Randolph", 
      "New Jersey", "07869", "908-748-9393", 
      "andrew@shawassociates.com", "shawassociates.com");

  System.out.println("Writing to resources/customer7-out.json...");
  OutputStream os = new FileOutputStream("resources/customer7-out.json");
  OutputStreamWriter outStream = new OutputStreamWriter(os);
  Gson gson1 = new Gson();
  writer = new JsonWriter(outStream);
  gson1.toJson(customer7, Customer.class, writer);
  
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (writer != null)
    try {
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
}

Output of Write Object to FileOutputStream in GSON

{"customerId":"007","firstName":"Andrew","lastName":"Shaw",
"address":"283 Licoln Blvd","city":"Randolph","state":"New Jersey",
"zipCode":"07869","phoneNumber":"908-748-9393","emailAddress":
"andrew@shawassociates.com","companyName":"shawassociates.com"}

The Customer Model (Customer.java)

This will be used to as the object which we store and retrieve in order to test out our application. I added it because I wanted my web service to store and retrieve some Java object.

package com.avaldes.model;

public class Customer {
  private String customerId;
  private String firstName;
  private String lastName;
  private String address;
  private String city;
  private String state;
  private String zipCode;
  private String phoneNumber;
  private String emailAddress;
  private String companyName;

  public Customer() { 
  }
  
  public Customer(String customerId, String firstName, String lastName,
      String address, String city, String state, String zipCode,
      String phoneNumber, String emailAddress, String companyName) {

    this.customerId = customerId;
    this.firstName = firstName;
    this.lastName = lastName;
    this.address = address;
    this.city = city;
    this.state = state;
    this.zipCode = zipCode;
    this.phoneNumber = phoneNumber;
    this.emailAddress = emailAddress;
    this.companyName = companyName;
  }

  public String getCustomerId() {
    return customerId;
  }

  public void setCustomerId(String customerId) {
    this.customerId = customerId;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  public String getCity() {
    return city;
  }

  public void setCity(String city) {
    this.city = city;
  }

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getZipCode() {
    return zipCode;
  }

  public void setZipCode(String zipCode) {
    this.zipCode = zipCode;
  }

  public String getPhoneNumber() {
    return phoneNumber;
  }

  public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }

  public String getEmailAddress() {
    return emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }

  public String getCompanyName() {
    return companyName;
  }

  public void setCompanyName(String companyName) {
    this.companyName = companyName;
  }

  @Override
  public String toString() {
    return "Customer [customerId=" + customerId + ", firstName="
        + firstName + ", lastName=" + lastName + ", address=" + address
        + ", city=" + city + ", state=" + state + ", zipCode=" + zipCode
        + ", phoneNumber=" + phoneNumber + ", emailAddress=" + emailAddress
        + ", companyName=" + companyName + "]";
  }
}

Complete Program (GsonToObjectExample.java)

package com.avaldes.tutorial;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import com.avaldes.model.Customer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;

public class GsonToObjectExample {
  public static void main(String[] args) {
    // Java Object to JSON String
    Customer customer1 = new Customer("001", "Amaury", 
        "Valdes", "100 Main Street", "Newark", 
        "New Jersey", "07044", "908-321-8080",
        "amaury.valdes@mail.com", "avaldes.com");

    Gson gson = new Gson();
    String json = gson.toJson(customer1, Customer.class);
    System.out.println(json);
    
    // Java Object to JSON String using GsonBuilder()
    Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
    json = prettyGson.toJson(customer1);
    System.out.println(json);
    
    // Read JSON to Object
    json = "{\"customerId\": \"002\", "
        + "\"firstName\":\"Jennifer\", "
        + "\"lastName\":\"Wilson\","
        + "\"address\":\"89 Maple Street\","
        + "\"companyName\":\"amazon.com\","
        + "\"city\":\"Plainsboro\","
        + "\"state\":\"New Jersey\","
        + "\"zipCode\":\"08873\","
        + "\"phoneNumber\":\"888-829-2828\","
        + "\"emailAddress\":\"jen.wilson@amazon.com\""
        + "}";
    Customer cust2 = gson.fromJson(json, Customer.class);
    System.out.println(cust2);
    
    // Read JSON from File
    Reader reader = null;
    FileInputStream in;
    try {
      in = new FileInputStream("resources/customer3.json");
      try {
        reader = new InputStreamReader(in, "UTF-8");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    Customer cust3 = gson.fromJson(reader, Customer.class);
    System.out.println(cust3);
    
    // Read JSON from Reader
    json = "{\"customerId\": \"004\", "
        + "\"firstName\":\"Dennis\", "
        + "\"lastName\":\"Hunter\","
        + "\"address\":\"15 Terhune Road\","
        + "\"city\":\"Clover\","
        + "\"state\":\"South Carolina\","
        + "\"zipCode\":\"29710\","
        + "\"companyName\":\"Arnold Furniture, Co.\","
        + "\"phoneNumber\":\"888-829-2828\","
        + "\"emailAddress\":\"dennis@arnold.com\""
        + "}";
    
    reader = new StringReader(json);
    Customer cust4 = gson.fromJson(reader, Customer.class);
    System.out.println(cust4);

    // Read JSON from InputStream (requires Reader)
    InputStream inStream = null;
    InputStreamReader inReader = null;
    try {
      inStream = new FileInputStream(
          "resources/customer5.json");
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
    }
    try {
      inReader = new InputStreamReader(inStream, "UTF-8");
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
    }
    Customer cust5 = gson.fromJson(inReader, Customer.class);
    System.out.println(cust5);
        
    // Read JSON from URL (requires Reader)
    try {
      inReader = new InputStreamReader(
          new URL("https://avaldes.com/data/customer6.json")
            .openStream());
      Customer cust6 = gson.fromJson(inReader, Customer.class);
      System.out.println(cust6);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
    
    // Write Object to FileOutputStream
    JsonWriter writer = null;
    try {
      Customer customer7 = new Customer("007", "Andrew", 
          "Shaw", "283 Licoln Blvd", "Randolph", 
          "New Jersey", "07869", "908-748-9393", 
          "andrew@shawassociates.com", "shawassociates.com");

      System.out.println("Writing to resources/customer7-out.json...");
      OutputStream os = new FileOutputStream("resources/customer7-out.json");
      OutputStreamWriter outStream = new OutputStreamWriter(os);
      Gson gson1 = new Gson();
      writer = new JsonWriter(outStream);
      gson1.toJson(customer7, Customer.class, writer);
      
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (writer != null)
        try {
          writer.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
  }
}

Download the Complete Source Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

google_gson_to_java

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *