Converting JSON to and From Java Object using Json-IO

Converting JSON to and From Java Object using JSON-IO

In this tutorial we will discuss how to Convert JSON to and from Java Object using JSON-IO. We will discuss various different mechanisms in order to serialize and deserialize JSON to/from Java Objects.

What’s Covered

  1. JSON IO Library
  2. Converting Java Object to JSON using JSON IO
  3. Removing JSON IO @Type
  4. Converting Java Object to JSON using formatJson in JSON IO for Pretty-Printing
  5. Converting JSON to Java Object in JSON IO
  6. Read JSON from InputStream in JSON IO
  7. Write Object to FileOutputStream in JSON IO
  8. 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
  • JSON IO 4.3.0 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.

json-io-4.3.0.jar

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

json_io_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.

json_io_proj_struct

JSON IO Library

JSON IO provides the functionality for performing the actual conversions between Java Objects and JSON equivalents. json-io consists of two main classes, a reader (JsonReader) and a writer (JsonWriter). There is a third class called JsonObject which is used mainly for Maps is also available. However, for most of the data in our tutorial, we will be using JsonReader/JsonWriter we can read and write JSON from Strings and Streams.

json-io does not require that Java classes implement Serializable or Externalizable in order to perform the serialization. It serializes Java object into JSON and retain all object details except transient fields which is identical behavior exhibited by Java’s ObjectOutputStream.

Converting Java Object to JSON using JSON IO

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

  • JsonWriter.objectToJson() performs the serialization, that is, converts a Java Object to its JSON string
  • JsonReader.jsonToJava() 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 JsonWriter.objectToJson() 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 customer = new Customer("001", "Amaury", 
		"Valdes","100 Main Street", "Newark", 
		"New Jersey", "07044", "908-321-8080",
		"amaury.valdes@mail.com", "avaldes.com");

String json = JsonWriter.objectToJson(customer);
System.out.println(json);

Output of Converting Java Object to JSON

{"@type":"com.avaldes.model.Customer","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"}

Removing JSON IO @Type

In this example, we use JsonWriter.objectToJson() class however we create a Map containing the argument JsonWriter.TYPE, false. We then use this Map (jsonArgs) as the second parameter to the objectToJson method.

// Modify JsonWriter to Remove @Type in JSON
Map<String, Object> jsonArgs = new HashMap<String, Object>();
jsonArgs.put(JsonWriter.TYPE, false);
json = JsonWriter.objectToJson(customer, jsonArgs);
System.out.println("Modify to remove @type output...");
System.out.println(json);

Output of Removing @Type Metadata from JSON

Modify to remove @type output...
{"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 formatJson in JSON IO for Pretty-Printing

In this example, we use JsonWriter.formatJson(json) method to format the JSON output with indentation for a nicer JSON presentation.

// Format PrettyPrinting
System.out.println(JsonWriter.formatJson(json));

Output of Converting Java Object to JSON using Pretty-Printing

{
  "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 JSON IO

json-io makes converting a JSON String very straight-forward and simple. We use the JsonReader.jsonToJava() method and pass the JSON string as the first parameter. This process will deserialize the JSON back to its Java Object equivalent.

// Read JSON from String
json = "{\"@type\":\"com.avaldes.model.Customer\","
		+ "\"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 cust = (Customer) JsonReader.jsonToJava(json);
System.out.println(cust);

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]

Read JSON from InputStream in JSON IO

An InputStream allows us to read characters from an input stream of bytes; In our example, we will be using FileInputStream which reads bytes from a file in the file system. The FileInputStream may read one or more bytes from the underlying byte-input stream, usually an InputStream.

Sample File (customer3.json)

{"@type":"com.avaldes.model.Customer","customerId":"003",
"firstName":"Daniel","lastName":"Jacobs","address":
"42 Maple Drive","city":"Kennisaw","state":"Georgia",
"zipCode":"30144","phoneNumber":"800-783-4444","emailAddress":
"daniel.jacobs@go.com","companyName":"ABC GO Services"}
// Read JSON From FileInputStream
InputStream inStream = null;
try {
	inStream = new FileInputStream(
			"resources/customer3.json");
	reader = new JsonReader(inStream);
	Customer cust2 = (Customer) reader.readObject();
	System.out.println(cust2);
} catch (FileNotFoundException e) {
	e.printStackTrace();
} finally {
	try {
		inStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

Output of Reading JSON from FileInputStream

Customer [customerId=003, firstName=Daniel, lastName=Jacobs, 
address=42 Maple Drive, city=Kennisaw, state=Georgia, zipCode=30144, 
phoneNumber=800-783-4444, emailAddress=daniel.jacobs@go.com, 
companyName=ABC GO Services]

Write Object to FileOutputStream in JSON IO

In this example, we will be serializing the object to JSON and writing it out to a FileOutputStream.

// Write Object to File
OutputStream outStream = null;
try {
	Customer customer4 = new Customer("004", "Jessica", 
			"Alba", "87 Woods Road", "Selena", "California", 
			"31003", "800-837-9300","jessica@alba.com", "alba.com");

	System.out.println("Writing to resources/customer4-out.json...");
	File file = new File("resources/customer4-out.json");
	outStream = new FileOutputStream(file);
	writer = new JsonWriter(outStream);
	writer.write(customer4);
} catch (IOException e) {
	e.printStackTrace();
} finally {
	try {
		outStream.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

Output of Write Object to FileOutputStream in JSON IO

{"@type":"com.avaldes.model.Customer","customerId":"004","firstName":
"Jessica","lastName":"Alba","address":"87 Woods Road","city":"Selena",
"state":"California","zipCode":"31003","phoneNumber":"800-837-9300",
"emailAddress":"jessica@alba.com","companyName":"alba.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.

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 (JsonIOToObjectExample.java)

package com.avaldes.tutorial;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.avaldes.model.Customer;
import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;

public class JsonIOToObjectExample {

  private static JsonReader reader;
  private static JsonWriter writer;

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

    String json = null;
    json = JsonWriter.objectToJson(customer);
    System.out.println(json);

    // Modify JsonWriter to Remove @Type in JSON
    Map<String, Object> jsonArgs = new HashMap<String, Object>();
    jsonArgs.put(JsonWriter.TYPE, false);
    json = JsonWriter.objectToJson(customer, jsonArgs);
    System.out.println("Modify to remove @type output...");
    System.out.println(json);
    
    // Format PrettyPrinting
    System.out.println(JsonWriter.formatJson(json));

    // Read JSON from String
    json = "{\"@type\":\"com.avaldes.model.Customer\","
        + "\"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 cust = (Customer) JsonReader.jsonToJava(json);
    System.out.println(cust);

    // Read JSON From InputStream
    InputStream inStream = null;
    try {
      inStream = new FileInputStream(
          "resources/customer3.json");
      reader = new JsonReader(inStream);
      Customer cust2 = (Customer) reader.readObject();
      System.out.println(cust2);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        inStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // Write Object to File
    OutputStream outStream = null;
    try {
      Customer customer4 = new Customer("004", "Jessica", 
          "Alba", "87 Woods Road", "Selena", "California", 
          "31003", "800-837-9300","jessica@alba.com", "alba.com");

      System.out.println("Writing to resources/customer4-out.json...");
      File file = new File("resources/customer4-out.json");
      outStream = new FileOutputStream(file);
      writer = new JsonWriter(outStream);
      writer.write(customer4);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        outStream.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!!!

json-io_to_java

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

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