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.

Share

Serialzing A Java Object Into XML and De-Serialzing using XMLEncoder And XMLDecoder

This is my third post related to Java Object Serialization.

In the first post, I talked about serializing a Java Object to a binary file system.

I dealt with serializing the object to MySQL database in my second post.

In this post, I am providing you a working code on how to write (serialize) a java object into XML file using java.beans.XMLEncoder and reading the XML File into Java Object using java.beans.XMLDecoder

The XMLDecoder class is used to read XML documents created using the XMLEncoder and is used just like the ObjectInputStream. For example, one can use the following fragment to read the first object defined in an XML document written by the XMLEncoder class.

The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects. Despite the similarity of their APIs, the XMLEncoder class is exclusively designed for the purpose of archiving graphs of JavaBeans as textual representations of their public properties. Like Java source files, documents written this way have a natural immunity to changes in the implementations of the classes involved. The ObjectOutputStream continues to be recommended for interprocess communication and general purpose serialization.

package com.kushal.serialization;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 10th September 2009
 *
 * Serializing Object To XML
 * Deserializing Object From XML
 */

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ObjectSerializationToXML {

	/**
	 * This method saves (serializes) any java bean object into xml file
	 */
	public void serializeObjectToXML(String xmlFileLocation,
			Object objectToSerialize) throws Exception {
		FileOutputStream os = new FileOutputStream(xmlFileLocation);
		XMLEncoder encoder = new XMLEncoder(os);
		encoder.writeObject(objectToSerialize);
		encoder.close();
	}

	/**
	 * Reads Java Bean Object From XML File
	 */
	public Object deserializeXMLToObject(String xmlFileLocation)
			throws Exception {
		FileInputStream os = new FileInputStream(xmlFileLocation);
		XMLDecoder decoder = new XMLDecoder(os);
		Object deSerializedObject = decoder.readObject();
		decoder.close();

		return deSerializedObject;
	}

	/**
	 * Testing.
	 * 1. Creates and Object.
	 * 2. Serializes Object To XML
	 * 3. Deserializes Object From XML
	 * 4. Prints The values hold in Object
	 */
	public static void main(String args[]) throws Exception {

		/* Location of XML File */
		String XMLLocation = "C:/myXMLFile.xml";

		ObjectSerializationToXML serializer = new ObjectSerializationToXML();

		/* Creating and filling a bean object */
		MyBeanToSerialize obj = new MyBeanToSerialize();
		obj.setFirstName("Johnny");
		obj.setLastName("Depp");
		obj.setAge(45);

		/* Serialzing Object to XML */
		System.out.println("Starting Serialization...");
		serializer.serializeObjectToXML(XMLLocation, obj);
		System.out.println("Serialized Object: " + obj.getClass().getName());
		System.out.println("Destination XML: " + XMLLocation);

		/* Reading the object from serialized XML */
		System.out.println("\n\nStarting De-Serialization...");
		System.out.println("Source XML: " + XMLLocation);
		MyBeanToSerialize deserializedObj = (MyBeanToSerialize) serializer
				.deserializeXMLToObject(XMLLocation);
		System.out.println("De-serialized Object: "
				+ deserializedObj.getClass().getName());
		System.out.println("\nChecking For Values In De-Serialized Object");
		System.out.println("...First Name: " + deserializedObj.getFirstName());
		System.out.println("...Last Name: " + deserializedObj.getLastName());
		System.out.println("...Age: " + deserializedObj.getAge());

	}

}

The following is the java bean that will be serialized / deserialized.

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 10th September 2009
 *
 * Simple Java Bean
 */
public class MyBeanToSerialize {
	private String firstName;
	private String lastName;
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	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;
	}

}

================================
Output of running the file ObjectSerializationToXML
Starting Serialization…
Serialized Object: com.kushal.serialization.MyBeanToSerialize
Destination XML: C:/myXMLFile.xml

Starting De-Serialization…
Source XML: C:/myXMLFile.xml
De-serialized Object: com.kushal.serialization.MyBeanToSerialize

Checking For Values In De-Serialized Object
…First Name: Johnny
…Last Name: Depp
…Age: 45

The content of the generated XML File:

Blog Widget by LinkWithin

Originally posted 2009-09-10 15:13:23.

Share