How to deserialize JSON using GSON (Java)

January 11, 2019

GSON helps deserializing JSON objects easily to POJO.

Install

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

Java to JSON

public class GsonToJson {
    ...

    public static void main(String[] args) {

        Map<Integer, String> colours = new HashMap<>();
        colours.put(1, "blue");
        colours.put(2, "yellow");
        colours.put(3, "green");
        
        Gson gson = new Gson();
        
        String output = gson.toJson(colours);
        
        System.out.println(output);
    }
    ...
}

JSON to Java

Sample JSON

{
    "firstName":"Alex",
    "lastName":"Nguyen"
}

Create Model

public final class User {
    @SerializedName("firstName")
    public final String firstName;
    @SerializedName("lastName")
    public final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

Deserialize

public class GsonFromJson {
    ... 

    public static void main(String[] args) {

        String json_string = "{\"firstName\":\"Alex\", \"lastName\": \"Nguyen\"}";

        Gson gson = new Gson();
        User user = gson.fromJson(json_string, User.class);

        System.out.println(user.firstName);
        System.out.println(user.lastName);
    }
    ...
}