Using Gson to convert Java objects to JSON and back. This tutorial explains how to use the Open Source framework Gson from Google to usage and purpose of Java JAR files.

1. Google Gson

1.1. What is 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 objects for which you do not have the source. For this purpose, Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type. A deserializers allows to convert from Java to a JSON representation. You can also configure Gson to use custom representations of your objects.

Gson allows to serialize a Collections of objects of the same type. As the generics information is persisted in the JSON you need to specify the type to which you want to serialize too.

To use Gson in a Gradle build, add the following as dependency to your build.gradle build file.

`compile 'com.google.code.gson:gson:2.8.1'`

1.2. Excluding fields from serialization and deserialization

By default, Gson tries to map all fields in the Java object to the JSON file it creates and vice versa. But Gson allows to exclude certain fields for serialization and deserialization. GSon can for example not serialize Java Beans, as the IPropertyChangeSupport field lead to an infinite loop. Therefore you must exclude such a field from the JSON conversion.

To exclude fields you have four options:

  • Use the transient keyword on your field to indicate that this field should not be serialized.

  • Gson provides an the @Expose from the com.google.gson.annotations package which allows to define which fields should be deserialized.

You can configure Gson to consider this annotation. * You can register a custom exclusion strategy with the GsonBuilder and its setExclusionStrategies method. For this you would implement the ExclusionStrategy and its houldSkipField(FieldAttributes f) and shouldSkipClass(Class clazz) methods. * You can define a custom annotation and tell GSon to ignore such fields.

1.3. Missing fields in JSON

Gson does not support the definition of a "required field". It sets the property to null in your deserialized object, if something is missing in the JSON.

To fail the conversion is case an object is missing in the JSON, you could create and register a customer deserializer and annotation. See http://stackoverflow.com/a/21634867/548637 for an example.

2. Exercise: Using Gson

2.1. Target of this exercise

In this exercise you use Gson to convert a data model into JSON and the JSON back to Java objects.

2.2. Create project and add library to it

Create a Java project, download the Gson library from its homepage and add it to the projects classpath.

2.3. Create the data model

Create the following data model.

package com.vogella.java.library.gson;

public class Task {
    private final long id;
    private String summary;
    private String description;
    private Status status;
    private int priority;

    public enum Status {
        CREATED, ASSIGNED, CANCELED, COMPLETED
    }

    public Task(long id, String summary, String description, Status status, int priority) {
        this.id = id;
        this.summary = summary;
        this.description = description;
        this.status = status;
        this.priority = priority;
    }

    public long getId() {
        return id;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String toString() {
        return "Task [id=" + id + ", summary=" + summary + ", description=" + description + ", status=" + status
                + ", priority=" + priority + "]";
    }

}

2.4. Write a converter main method

Write the following class to test the conversion.

package com.vogella.java.library.gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;



public class MainTest {

    public static void main(String[] args) {
        List<Task> list = new ArrayList<Task>();
        for (int i = 0; i < 20; i++) {
            list.add(new Task(i, "Test1", "Test2", Task.Status.ASSIGNED, 10));
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<Task>>() {}.getType();
        String json = gson.toJson(list, type);
        System.out.println(json);
        List<Task> fromJson = gson.fromJson(json, type);

        for (Task task : fromJson) {
            System.out.println(task);
        }
    }
}

3. Exercise: Exclude a field from a Java object

The following is your data model.

package com.vogella.tasks.model;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Date;
import java.util.Objects;

public class Todo {


    private PropertyChangeSupport changes = new PropertyChangeSupport(this);


    public static final String FIELD_ID = "id";

    public static final String FIELD_SUMMARY = "summary";

    public static final String FIELD_DESCRIPTION = "description";

    public static final String FIELD_DONE = "done";

    public static final String FIELD_DUEDATE = "dueDate";

    public final long id;
    private String summary ="" ;
    private String description ="";
    private boolean done = false;
    private Date dueDate;

    public Todo(long i) {
        id = i;
    }

    public Todo(long i, String summary, String description, boolean b, Date date) {
        this.id = i;
        this.summary = summary;
        this.description = description;
        this.done = b;
        this.dueDate = date;
    }



    public long getId() {
        return id;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        changes.firePropertyChange(FIELD_SUMMARY, this.summary,
                this.summary = summary);
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        changes.firePropertyChange(FIELD_DESCRIPTION, this.description,
                this.description = description);
    }

    public boolean isDone() {
        return done;
    }

    public void setDone(boolean isDone) {
        changes.firePropertyChange(FIELD_DONE, this.done, this.done = isDone);
    }

    public Date getDueDate() {
        return dueDate;
    }

    public void setDueDate(Date dueDate) {
        changes.firePropertyChange(FIELD_DUEDATE, this.dueDate,
                this.dueDate = dueDate);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (int) (id ^ (id >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Todo other = (Todo) obj;
        if (id != other.id)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Todo [id=" + id + ", summary=" + summary + "]";
    }

    public Todo copy() {
        return new Todo(id, summary, description, done, dueDate);
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }
}

Via the following class you can deserialize and serialize this data model into JSON and back to Java. In this example we exclude the field for the IPropertyChangeSupport.

package com.vogella.maven.lars;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class ExampleConvertor {

    private static class MyCustomExclusionStrategy implements ExclusionStrategy {

        public boolean shouldSkipClass(Class<?> arg0) {
            return false;
        }

        public boolean shouldSkipField(FieldAttributes f) {
            return (f.getDeclaringClass() == Todo.class && f.getName().equals("changes"));
        }

    }

    private static int current;

    public static void main(String[] args) {
        List<Todo> list = new ArrayList<Todo>();
        list.add(createTodo("Application model", "Flexible and extensible"));
        list.add(createTodo("DI", "@Inject as programming mode"));
        list.add(createTodo("OSGi", "Services"));
        list.add(createTodo("SWT", "Widgets"));
        list.add(createTodo("JFace", "Especially Viewers!"));
        list.add(createTodo("CSS Styling", "Style your application"));
        list.add(createTodo("Eclipse services", "Selection, model, Part"));
        list.add(createTodo("Renderer", "Different UI toolkit"));
        list.add(createTodo("Compatibility Layer", "Run Eclipse 3.x"));

        // Add .excludeFieldsWithoutExposeAnnotation() to exclude fields not annotated with @Expose
        Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(new MyCustomExclusionStrategy()).create();
        Type type = new TypeToken<List<Todo>>() {}.getType();
        String json = gson.toJson(list, type);
        try {
            Files.write(Paths.get("db.txt"), json.getBytes(), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String content ="";
        try {
            content = new String(Files.readAllBytes(Paths.get("db.txt")));
        } catch (IOException e) {
            e.printStackTrace();
        }


        System.out.println(content);
    }

    private static Todo createTodo(String summary, String description) {
        return new Todo(current++, summary, description, false, new Date());
    }

}