Tech: Google gson

It has come to my attention that some of my readers would prefer to know upfront if a post I am making is technical in nature or not. Thus the reason for the prefix to this post’s title. I will quickly discuss Google’s json library for Java, code-named gson. I like the simplicity of the library, especially if you are not using a framework that handles everything for you (like jersey).

*Note that I use a helper method for printing out values to the console

public static void out(Object...objects) {
    for (Object object:objects) {
        System.out.print(object + " ");
    }
    System.out.println();
}

To start you need to include the library

<!--  GsonExample: Java to Json conversion -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2</version>
    <scope>compile</scope>
</dependency>

Then you need to instantiate the serializer / deserializer

 Gson gson = new Gson();

Basic Serialization

out("Serialization");
out(gson.toJson(1));            // prints 1
out(gson.toJson("abcd"));       // prints abcd
out(gson.toJson(new Long(10))); // prints 10

The gson.toJson method has been overloaded to handle many parameters for conversion. There are some difficulties with generic types and arbitrary types.

Basic Deserialization

out("Deserialization");
int iOne = gson.fromJson("1", int.class);
Integer iOne1 = gson.fromJson("1", Integer.class);
Long lOne = gson.fromJson("1", Long.class);
Boolean bFalse = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);

The gson.fromJson method has been templatized (generics) to convert json to various object types. As we shall see later it handles custom objects as well.

Array Examples

out("Array Examples");
int[] values = {1,2,3};
out(gson.toJson(values)); // prints [1,2,3]
String[] strArray = gson.fromJson("[\"abc\"]", String[].class);
int[] intArray = gson.fromJson("[1,2,3,4]", int[].class);

To be honest, this is the first time I have ever written String[].class in Java. It is nice that arrays are handled in this way, as it keeps to the standard way of using the library and is still easy to use & understand.

Object Examples

static class BagOfPrimitives {
    private int value1 = 1;
    private String value2 = "abc";
    private transient int value3 = 3;
}

out("Object Examples");
BagOfPrimitives obj = new BagOfPrimitives();
String json = gson.toJson(obj)  ;
out(json); // prints {"value1":1,"value2":"abc"}
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);

This is most probably what I use the most, not quite like in this example, but the object serialization – deserialization. It is fantastic that there is no “markup” on your code (annotations). You can make changes to the normal POJO without worrying too much about if it will serialize or not. There are some caveats, alluded to above, discussed in detail on the gson user guide.

Full Example

package avdw.example;

import com.google.gson.Gson;

import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * User: Andrew
 * Date: 2012/05/10
 * Time: 10:09 AM
 * To change this template use File | Settings | File Templates.
 */
public class GsonExample {

    public static void main(String[] args) {
        Gson gson = new Gson();

        out("Serialization");
        out(gson.toJson(1));            // prints 1
        out(gson.toJson("abcd"));       // prints abcd
        out(gson.toJson(new Long(10))); // prints 10

        out();
        out("Deserialization");
        int iOne = gson.fromJson("1", int.class);
        Integer iOne1 = gson.fromJson("1", Integer.class);
        Long lOne = gson.fromJson("1", Long.class);
        Boolean bFalse = gson.fromJson("false", Boolean.class);
        String str = gson.fromJson("\"abc\"", String.class);

        out();
        out("Array Examples");
        int[] values = {1,2,3};
        out(gson.toJson(values)); // prints [1,2,3]
        String[] strArray = gson.fromJson("[\"abc\"]", String[].class);
        int[] intArray = gson.fromJson("[1,2,3,4]", int[].class);

        out();
        out("Object Examples");
        BagOfPrimitives obj = new BagOfPrimitives();
        String json = gson.toJson(obj)  ;
        out(json); // prints {"value1":1,"value2":"abc"}
        BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
    }

    static class BagOfPrimitives {
        private int value1 = 1;
        private String value2 = "abc";
        private transient int value3 = 3;
    }

    public static void out(Object...objects) {
        for (Object object:objects) {
            System.out.print(object + " ");
        }
        System.out.println();
    }
}
  • Sihu5

    That means, we always need to define the Class we want to deserialze the Json string to in the client code. I mean, I was hoping that Json would some how figure out the type of the class BagOfPrimitives by itself :) 

    • http://www.avanderw.co.za/ Andrew van der Westhuizen

      Very unfortunate I agree. Java is the reason it needs to be defined, strong typing does have pros and cons. However, if you send it on to the browser, you can just use it in Javascript, although if you are then debugging a year later, you will not know what all is in the object unless you query the service providing the JSON. Having a photographic memory makes the case moot though.