Gson tutorial

Posted on Updated on

Google GSON is JSON parser and generator for java. Google developed GSON for internal use but later open sourced. Gson is relatively easy to use, it contains multiple APIs which you can use to work with JSON. In this GSON tutorial we will go through how to use GSON to parse JSON into Java objects and serialize Java objects into JSON.

These are few topics which we will discussing in this tutorial.

  1. Creating a GSON object.
  2. Converting JSON into Java Objects.
  3. Generating JSON from Java Objects.
  4. Pretty printing.
  5. Custom Instance creators in GSON.
  6. Custom Serialization and Deserialization.
  7. Version support in GSON.

Create simple POJO which we will use further in our tutorial.

  1. Creating a GSON object.

    There are two ways to create a Gson object.

    1. Using new Gson()
    2. Creating a GsonBuilder instance and calling create() on it.
    1. new Gson()

      We can create Gson object simply by calling default constructor of Gson class. Similar to other class in Java we can create object of Gson.

    2. GsonBuilder.build()

      Another way to create a Gson instance is to create a GsonBuilder() and call its create() method. Below is an example to create a GsonBuilder and calling create().

      Once object of Gson is created we can use it to parse and generate JSON.

  2. Converting JSON into Java Objects.

    Using the fromJson() method of Gson API we can parse JSON string into java object. Here is an example of converting JSON into Java object.

    There are two parameters in fromJson() method. The first parameter is json String which we want to parse and the second parameter is Java class to parse JSON string.

  3. Generating JSON from Java Objects.

    Using the toJson() method of Gson API we can convert java objects into JSON string. Here is an example to generate JSON from java objects.

    One parameter we are passing into toJson() method is the java object which we want to convert into JSON string.

    You can find more examples like convert List, Map and any other object to/from json using gson in our tutorial convert object to/from json using gson.

  4. Pretty printing.

    Gson provide JSON output in compact format which you can see in above example is not contains any whitespace or intonation. So, the default output is not very much readable to developers. However in case we want to format the output of Gson we can use setPrettyPrinting() method of GsonBuilder class.

  5. Custom Instance creators in GSON.

    While parsing JSON String to or from Java object, By default Gson try to create instance of Java class by calling default constructor. In case Java class doesn’t contain default constructor or you want to do some initial configuration while creating Java objects, you need to create and register your own instance creator.

    POJO class which don’t have default constructor.

    Instance creator class for Address.

    Now test the code.

  6. Custom Serialization and Deserialization.

    Now a days complex applications are build where different teams are collaborating with each other to make a project successful. There are some scenarios where UI team created their UI component expecting value of isActive field will be ‘Y’ or ‘N’ while as a backend developer you have created your bean for isActive field as boolean. So while converting the bean to JSON string with isActive as boolean UI team gets true or false value.To handle this kind of scenario Gson come with the concept of Custom Serialization and Deserialization.

    First create a bean User with userName as string and isActive as boolean.

    Custom Serializer.

    To create custom serializer in Gson you have to implement the JsonSerializer interface which looks like

    Here value field in method serialize means the data type of field you want to serialize.
    Customer BooleanSerializer which converts true value to “Y” and false to “N”.

    Now we need to register this custom serializer class to GsonBuilder class before creating the gson instance from the gsonBuilder. Below example demonstrates this.

    So, you can see we have created user object with username as “rahul” and has set as Active user with value true.In output userName is coming as rahul while isActive field populated as Y. So, our custom serializer is working.

    Custom Deserializer

    In Custom serializer section we have converted User class to Json String where values of isActive field replaced with Y or N. Now if we want to convert ‘{“userName”:”rahul”,”isActive”:”N”}’ JSON string back to User class which has isActive field as boolean, you have to write custom deserializer class.
    To create custom serializer in Gson you have to implement the JsonDeserializer interface which looks like.

    Customer BooleanDeserializer which converts “Y” to true and “N” to false.

    Now we need to register this custom deserializer class to GsonBuilder class before creating the gson instance from the gsonBuilder. Below example demonstrates this.

  7. Version support in Gson

    Gson supports version control while reading and writing Java objects. Version support is very useful when we are working in a group where lots of other applications interacting with your code and you are changing your Java bean frequently to support them. For version control in Gson you have to annotate your fields with version number then Gson includes or exclude fields based on their version number while converting JSON string to Java object and vice versa.You have to use @Since annotation in your Java classes for version support. Let modify our Emp class with @Since annotation.

    So we have annotated Id, firstName and lastName with version 1.0 while Address with version 2.0.
    Now while creating Gson object you have to use GsonBuilder where you can set version control to create gson object as below example.

    Gson instance created from GsonBuilder which is created with version number 1.0 will include id, fisrtName and lastName as these fields are annotated with @Since(1.0). It excludes address fields as it is annotated with @Since(2.0).
    Let’s create object of Emp class and see generated json String.

    As you can see in the above code we have created object of Address class and set it to emp object. In output we have JSON String which contains id, firstName and lastName fields. So, while converting Java object to JSON string Gson exclude address field as it is annotated with @Since(2.0).

    Let use the same gson object to convert JSON string with address field to Java object.

    In output you can see id, firstName and lastName are populated while Address is not. So Gson supports version control while converting Java Object to JSON string and vice versa.

Stay tuned for more examples and tutorial related with Gson.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.