How to serialize Java objects into JSON format using Google’s GSON

JSON which is an abbreviated form of ‘JavaScript Object Notation’, is a text-based open standard designed for human-readable data interchange. Even though the name has the word JavaScript, JSON is not particularly tied to one language.The JSON format was originally specified by Douglas Crockford, and is described in RFC 4627. The official Internet media type for JSON is application/json. The JSON filename extension is .json.The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML. [Wikipedia]

In this article, I will talk about how you can use Java and Google’s Gson to convert (Serialize) Java Objects into JSON format
Let’s say we have a class called ‘SomeClass’. In this class, I have created several variables – string, integer, some simmple list, a complex list and a map of strings.

package com.kushal.tools.published;

public class SomeClass {

    private String helloString = "Hello";
    private int id = 123;
    private List simpleList = new ArrayList();
    private List complexList = new ArrayList();
    private Map<String, String> countryCapitalMap = new HashMap<String, String>();

    // To get helloString in JavaScript use data.helloString

    public SomeClass() {

        //Prepare a simple List
        simpleList.add("Chicago");
        simpleList.add("New York");
        simpleList.add("Boston");

        //Prepare a complex List Object - List of List of String in this case
        List tempListCities = new ArrayList();
        tempListCities.add("Des Moines");
        tempListCities.add("Iowa City");
        tempListCities.add("Ames");

        complexList.add(tempListCities);

        List tempListActors = new ArrayList();
        tempListActors.add("Johnny Depp");
        tempListActors.add("Robert DeNiro");
        tempListActors.add("Al Pacino");

        complexList.add(tempListActors);

        //Prepare some maps
        countryCapitalMap.put("Nepal", "Kathmandu");
        countryCapitalMap.put("Canada", "Ottawa");

    }

    public String getHelloString() {

        return helloString;
    }

    public void setHelloString(String helloString) {

        this.helloString = helloString;
    }

    public int getId() {

        return id;
    }

    public void setId(int id) {

        this.id = id;
    }

    public List getSimpleList() {

        return simpleList;
    }

    public void setSimpleList(List simpleList) {

        this.simpleList = simpleList;
    }
}

Let’s say we would like to serialize this class to some text format using JSON. Since JSON itself is the object notation language but not the tool itself, we need some tools that can convert this class to the JSON format.

Google has a tool called Gson. 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. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Gson Goals

  1. Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  2. Allow pre-existing unmodifiable objects to be converted to and from JSON
  3. Extensive support of Java Generics
  4. Allow custom representations for objects
  5. Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

[Text Source: Google]

Having noted that, we now will be using Gson library to convert the class above to JSON format.

Here is the utility class that can do this conversion. I am using gson-2.2.2.jar

package com.kushal.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

/**
 * @author Kushal Paudyal
 * Tested with gson-2.2.2.jar
 *
 */

public class SimpleGsonTutorial {

    public static void main(String args[]) {

        Gson gson = new Gson();
        String jsonString = gson.toJson(new SomeClass());

        System.out.println(jsonString);
    }

}


Here is the output of this program when you run it. The output is the serialized JSON string for our SomeClass java object.

{"helloString":"Hello",
"id":123,
"simpleList":["Chicago","New York","Boston"],
"complexList":[["Des Moines","Iowa City","Ames"],["Johnny Depp","Robert DeNiro","AlPacino"]],
"countryCapitalMap":{"Nepal":"Kathmandu","Canada":"Ottawa"}}


Note that Gson also allows you to create a java object from the JSON format. They have a fromGson() method that can do this reverse conversion.

Java Object Serialization and Deserialization In MySQL Database

In my previous article, I showed how any java object can be serialized to a file system, and how to read the object once it has been written to the file.

In this article, I am providing you a working code that I wrote and tested which stores java object into the database. I tested this coder the mysql database. There is no reason why it should not work for other databases.

The following is a summary of what is covered in this example:

  • Query to create tables in database for the purpose of storing java objects.
  • Query to write java objects to the database
  • Query to read java objects from the database
  • Basic mechanism of connecting to the database from Java Application
  • How to write Java Object to the database using prepared statements
  • How to read the Java Objects from the database using prepared statements.
  • You will see that the objects will be stored in database in the form of BLOB data type.

The following is a working code fully compiled and tested. Make sure to change the database credentials, url and name to suit your environment.

package com.kushal.serialization
/**SQL to create MySQL Table For Object Storing**/

/*CREATE TABLE javaobjects (
 objectid INT AUTO_INCREMENT,
 object_name varchar(100),
 object_value BLOB,
 primary key (objectid));
 */

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ObjectSerializationToMySQL {
	static final String SQL_TO_WRITE_OBJECT = "INSERT INTO JAVAOBJECTS(OBJECT_NAME, OBJECT_VALUE) VALUES (?, ?)";
	static final String SQL_TO_READ_OBJECT = "SELECT OBJECT_VALUE FROM JAVAOBJECTS WHERE OBJECTID = ?";

	static String driver = "com.mysql.jdbc.Driver";
	static String url = "jdbc:mysql://localhost/generaldb";
	static String username = "root";
	static String password = "root";

	/**
	 * This class will create and return a database connection.
	 */
	public static Connection getConnection() throws Exception {
		Class.forName(driver);
		Connection conn = DriverManager.getConnection(url, username, password);
		return conn;
	}

	/**
	 * This method will write a java object
	 * to the database
	 * Parameters: connection object and object to be serialized
	 */
	public static long writeJavaObject(Connection conn, Object object)
			throws Exception {
		String className = object.getClass().getName();
		PreparedStatement pstmt = conn.prepareStatement(SQL_TO_WRITE_OBJECT);
		pstmt.setString(1, className);
		pstmt.setObject(2, object);
		pstmt.executeUpdate();
		ResultSet rs = pstmt.getGeneratedKeys();
		int id = -1;
		if (rs.next()) {
			id = rs.getInt(1);
		}
		rs.close();
		pstmt.close();
		System.out.println("Serialization Successful."+
						   "Serialized Class: "+ className);
		return id;
	}

	/**
	 * This class will de-serialize a java object from the database
	 */
	public static Object readJavaObject(Connection conn, long id)
			throws Exception {
		PreparedStatement pstmt = conn.prepareStatement(SQL_TO_READ_OBJECT);
		pstmt.setLong(1, id);
		ResultSet rs = pstmt.executeQuery();
		rs.next();
		byte[] buf = rs.getBytes("object_value");
		ObjectInputStream objectIn = null;
		if (buf != null)
			objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
		Object object = objectIn.readObject();
		String className = object.getClass().getName();
		rs.close();
		pstmt.close();
		System.out.println("Deserialization Successful."+
							"nDeserialized Class: "+ className);
		return object;
	}

	/**
	 * Testing the serialization and deserialization feature.
	 */

	public static void main(String args[]) throws Exception {
		Connection conn = null;
		try {
			/**Creating DB Connection**/
			conn = getConnection();
			conn.setAutoCommit(false);
			/**Creating Test object to Serialize**/
			MyObjectToSerialize obj = new MyObjectToSerialize("Roberto",
					"Armando", 35);
			/**
			 * Serializing the object and getting the database id,
			 * which is nothing but an autogenerated key
			 */
			long objectID = writeJavaObject(conn, obj);
			conn.commit();
			System.out.println("Serialized object ID" + objectID);
			/**
			 * Reading the object from database.
			 * This object is just serialized into database above.
			 */

			MyObjectToSerialize objFromDatabase = (MyObjectToSerialize) readJavaObject(
					conn, objectID);
			System.out.println("After Deserialization:");
			System.out.println("Object Value: " + objFromDatabase);
			System.out.println("Class: " + objFromDatabase.getClass().getName());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			/**Closing the database connection**/
			conn.close();
		}
	}
}

The following is the class which is serialized/de-serialized using the class above. Please note that any class which has to be serialized needs to implement Serialization interface.  Please refer to my previous article for further details

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 */
import java.io.Serializable;
public class MyObjectToSerialize implements Serializable {

	private String firstName;
	private String lastName;
	private int age;
	public MyObjectToSerialize(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	public String toString() {
		return firstName + " " + lastName + ", " + age;
	}
}

===========
Output of this program:
Serialization Successful.Serialized Class: com.kushal.serialization.MyObjectToSerialize
Serialized object ID6
Deserialization Successful.
Deserialized Class: com.kushal.serialization.MyObjectToSerialize
After Deserialization:
Object Value: Roberto Armando, 35
Class: com.kushal.serialization.MyObjectToSerialize


Content of the database after running the program:

Object Serialization And De-Serialization In Java To Filesystem

Object Serialization:
In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward.

This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

Advantages Of Object Serialization:
Serialization has a number of advantages. It provides:

  • A method of persisting objects which is more convenient than writing their properties to a text file on disk, and re-assembling them by reading this back in.
  • A method of issuing remote procedure calls, e.g., as in SOAP
  • A method for distributing objects, especially in software componentry such as COM, CORBA, etc.
  • A method for detecting changes in time-varying data.

Serialization In Java:
Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as “okay to serialize,” and Java then handles serialization internally. There are no serialization methods defined on the Serializable interface, but a serializable class can optionally define methods with certain special names and signatures that if defined, will be called as part of the serialization/deserialization process. The language also allows the developer to override the serialization process more thoroughly by implementing another interface, the Externalizable interface, which includes two special methods that are used to save and restore the object’s state.

There are three primary reasons why objects are not serializable by default and must implement the Serializable interface to access Java’s serialization mechanism.

  • Not all objects capture useful semantics in a serialized state. For example, a Thread object is tied to the state of the current JVM. There is no context in which a deserialized Thread object would maintain useful semantics.
  • The serialized state of an object forms part of its class’s compatibility contract. Maintaining compatibility between versions of serializable classes requires additional effort and consideration. Therefore, making a class serializable needs to be a deliberate design decision and not a default condition.
  • Serialization allows access to non-transient private members of a class that are not otherwise accessible. Classes containing sensitive information (for example, a password) should not be serializable or externalizable.


The standard encoding method uses a simple translation of the fields into a byte stream. Primitives as well as non-transient, non-static referenced objects are encoded into the stream. Each object that is referenced by the serialized object and not marked as transient must also be serialized; and if any object in the complete graph of non-transient object references is not serializable, then serialization will fail. The developer can influence this behavior by marking objects as transient, or by redefining the serialization for an object so that some portion of the reference graph is truncated and not serialized.

It is possible to serialize Java objects through JDBC and store them into a database.

While Swing components do implement the Serializable interface, they are not portable between different versions of the Java Virtual Machine. As such, a Swing component, or any component which inherits it, may be serialized to an array of bytes, but it is not guaranteed that this storage will be readable on another machine. [Source of this text Wikipedia]

The following program demonstrates how any object can be serialized. The first class is a simple object which has to be serialized/deserialized. The second class serializes and saves the object to the file, and then reads the object back from the file.

The Object to Serialize

package com.kushal.serialization;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 */
import java.io.Serializable;

public class MyObjectToSerialize implements Serializable {

	private String firstName;

	private String lastName;

	private int age;

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

	public String toString() {
		return firstName + " " + lastName + ", " + age;
	}

}

That Class that does the serialization/deserialization job.

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 *
 * A class that saves and loads a serialized object.
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSerialization {

	/**
	 * Saves an object to the file
	 */
	private static void saveObject(Serializable object, String filename)
			throws IOException {
		ObjectOutputStream objstream = new ObjectOutputStream(
				new FileOutputStream(filename));
		objstream.writeObject(object);
		objstream.close();
	}

	/**
	 * Loads an object from the file
	 */
	private static Object loadObject(String filename)
			throws ClassNotFoundException, IOException {
		ObjectInputStream objstream = new ObjectInputStream(
				new FileInputStream(filename));
		Object object = objstream.readObject();
		objstream.close();
		return object;
	}

	public static void main(String[] args) {
		MyObjectToSerialize original = new MyObjectToSerialize("Christopher","Walken", 64);
		System.out.println("Original Object:t" + original);
		try {
			saveObject(original, "C:/object.ser");
			MyObjectToSerialize loaded = (MyObjectToSerialize) loadObject("C:/object.ser");
			System.out.println("Loaded Object:tt" + loaded);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



Java serialization and version control:
The Java serialization mechanism provides an approach for version control. At the heart of Java serialization is the ObjectOutputStream class. It implements the computeSerialVersionUID() method to compute the suid during object serialization. This computed suid is then written to the serialized stream as a part of the serialized object. This suid in the stream serves as a marker to denote the version of the serializable class with which it is compatible. See Figure 2 for a sample of metadata stored in a serialized object. [Source of this text: JavaWorld]