Serialise Java Object to JSON using 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. In this tutorial we will show you how you can serizalise Java object to JSON using GSON.

Maven dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.6.2</version>
</dependency>

Object to be Serialized

Google GSON supports pre-existing objects. This means that we do not need to annotate our classes with any special marker annotations. If a field is marked transient, by default it is ignored and not included in the JSON serialization or deserialization. And while serialization, a null field is skipped from the output.

package com.memorynotfound.json;

import java.util.Date;

public class Product {

    private long id;
    private String name;
    private Date created;
    private double amount;

    public Product(long id, String name, Date created, double amount) {
        this.id = id;
        this.name = name;
        this.created = created;
        this.amount = amount;
    }
}

Serialize Java Object to JSON using GSON

  • You can not serialize objects with circular references since that will result in infinite recursion.
  • Google GSON supports pre-existing objects. This means that we do not need to annotate our classes with any special marker annotations.
  • Transient fields are by default ignored when serializing or deserializing.
  • While serialization, a null field is skipped from the output.
  • While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null.
  • Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization.
package com.memorynotfound.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Date;

public class ConvertObjectToJson {

    public static void main(String... args){
        Product product = new Product(1, "Playstation 4", new Date(), 499.99);
        Gson gson = new GsonBuilder().create();
        String result = gson.toJson(product);
        System.out.println(result);
    }
}

Output

{"id":1,"name":"Playstation 4","created":"Dec 26, 2014 2:20:00 PM","amount":499.99}

References

You may also like...