Google Gson for converting Java objects to JSON and JSON to Java Objects

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 is an Open Source project, which can be found under https://github.com/google/gson The webpage provides a convenient download link.

Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. For this purpose Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type and 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. For this you have different options.

To use Gson in a Gradle build, add compile ‘com.google.code.gson:gson:2.6.2’ or a later version as dependency to your build.gradl e build file

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 not 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.

Exercise: Using Gson
Target of this exercise
In this exercise you use Gson to convert a data model into JSON and the JSON back to Java objects.

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.

Create the data model

Create the following data model.

package com.mycodetips.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 + "]";
}

}

Write a converter main method
Write the following class to test the conversion.

package com.mycodetips.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 list = new ArrayList();
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>() {}.getType();
String json = gson.toJson(list, type);
System.out.println(json);
List fromJson = gson.fromJson(json, type);

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

Exercise: Exclude a field from a Java object
The following is your data model.

package com.example.e4.rcp.todo.model;

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

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.mycodetips.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 list = new ArrayList();
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>() {}.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());
}

}