Deserialise JSON to Java Object 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 deserialise JSON to Java Object using GSON.

Maven dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.memorynotfound.json.gson</groupId>
    <artifactId>convert-json-object</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <gson.version>2.3.1</gson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${gson.version}</version>
        </dependency>
    </dependencies>
</project>

Object to be Deserialised

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

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", created=" + created +
                ", amount=" + amount +
                '}';
    }
}

Serialise Java Object to JSON using GSON

package com.memorynotfound.json;

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

public class ConvertJsonToObject {

    public static void main(String... args){
        String json = "{\"id\":1,\"name\":\"Playstation 4\",\"created\":\"Dec 26, 2014 1:58:32 PM\",\"amount\":499.99}";
        Gson gson = new GsonBuilder().create();
        Product result = gson.fromJson(json, Product.class);
        System.out.println(result);
    }
}

Output

Product{id=1, name='Playstation 4', created=Fri Dec 26 13:58:32 CET 2014, amount=499.99}

References

You may also like...