Gson is a very powerful library to map data structures represented as JSON to Java objects. Of course, it also supports the other way around and can create an appropriate JSON representation of your Java objects.
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.
There are 4 key packages in Gson
com.google.gson
provides the Gson class to convert Json to Java and vice-versa.com.google.gson.annotations
provides annotations that can be used with Gson.com.google.gson.reflect
provides utility classes for finding type information for generic types.com.google.gson.stream
. Before we can get started, we need to pull in the Gson library to our project. At the time of writing, the latest version is 2.8.0. If you're using Gradle, add the following line:
compile 'com.google.code.gson:gson:2.8.0'
To get Gson we can simply use the constructor:
Gson gson = new Gson();
or use GsonBuilder
. We can use this builder to construct a Gson instance when we need to set configuration options other than the default.
For Gson with default configuration, it is simpler to use new GsonBuilder().create()
method.
Gson gson = new GsonBuilder().create();
Following is difference between GsonBuilder
and Gson
GsonBuilder
comes with various settings to control the data convertion like: serializing nulls, setting custom DateFormat
, version control, setting field naming policy, disabling HTML escaping, excudling some fileds for JSON convertion, etc.Basics of Java - JSON serialization
So let's do some serialization! Serialization in the context of Gson means mapping a Java object to its JSON representation. Below is plain Movie
object
public class Movie { public String title; public float rating; public int year; public Movie(String title, float rating, int year) { this.title = title; this.rating = rating; this.year = year; } }
First of all, we need to create a Java object for movie
Movie movie = new Movie("The Godfather", 9.2, 1972);
In order to do the serialization, we need a Gson object, which handles the conversion. We can simply use the constructor:
Gson gson = new Gson();
Next, we need to call the function toJson()
and pass the Movie
object
String movieJson = gson.toJson(movie);
Let's serialize list
Gson gson = new Gson(); List<Movie> list = new ArrayList<Movie>(); for (int i = 0; i < 5; i++) { list.add(new Movie("Movie " + i, 8.0, 2016)); } Type type = new TypeToken<List<Movie>>() {}.getType(); String jsonList = gson.toJson(list, type); System.out.println(json);
Gson changed the order of the properties (to alphabetically), but the content is identical!
Basics of JSON - Java deserialization
First of all, we need to create a String
, which contains the JSON:
String movieJson = "{'title': 'The Godfather', 'rating': 9.2, 'year': 1972}";
The next step is to create a Gson instance
Gson gson = new Gson();
Finally, we've to map from a JSON to a Java object with fromJson()
Movie movie = gson.fromJson(movieJson, Movie.class);
Let's deserialize list
List<Movie> fromJson = gson.fromJson(jsonList, type); for (Movie movie : fromJson) { System.out.println(movie); }
The @Expose annotation
The Gson @Expose
annotation can be used to mark a field to be exposed or not (included or not) for serialized or deserialized.
The @Expose
annotation can take two parameters. Each parameter is a boolean which can take either the value true or false. Here are some Gson @Expose
annotation examples.
Here is an example class using the GSON @Expose annotation:
public class Movie { @Expose(serialize = true, deserialize = true) public String title; @Expose(serialize = true, deserialize = true) public float rating; @Expose(serialize = false, deserialize = false) public int year; public Movie(String title, float rating, int year) { this.title = title; this.rating = rating; this.year = year; } }
@Expose
annotation placed above the fields, telling whether the given field should be included when serialized or deserialized.
In order to get GSON to react to the @Expose
annotations you must create a Gson instance using the GsonBuilder
class.
Let's see how to create it
GsonBuilder builder = new GsonBuilder(); builder.excludeFieldsWithoutExposeAnnotation(); Gson gson = builder.create();
Version support in Gson
Gson providing a simple versioning system for the Java objects that it reads and writes. Gson providing an annotation named @Since for the versioning concept @Since(versionnumber)
.
Way to create Gson instance with versioning
Gson gson = new GsonBuilder().setVersion(double versionnumber).create();
The above setVersion(versionnumber)
will works like this. Assume we mentinoed like this setVersion(2.0)
means all the fileds having 2.0 or less are eligible to parse.
Here is an example Movie
class with its fields annotated with the @Since
annotation:
public class Movie { @Since(1.0) public String title; @Since(1.0) public float rating; @Since(1.0) public int year; @Since(2.0) public String genre; public Movie(String title, float rating, int year, String genre) { this.title = title; this.rating = rating; this.year = year; this.genre = genre; } }
Second, we must create a GsonBuilder
and tell it what version it should be serializing to and deserializing from.
Gson gson = new Gson(); GsonBuilder builder = new GsonBuilder(); gson = builder.setVersion(1.0).create(); System.out.println("1.0 " + gson.toJson(obj)); gson = builder.setVersion(2.0).create(); System.out.println("2.0 " + gson.toJson(obj));
Serializing Null fields
By default the Gson object does not serialize fields with null
values to JSON. If a field in a Java object is null
, Gson excludes it.
You can force Gson to serialize null
values via the GsonBuilder
. Here is an example showing how to force serialization of null values with GSON:
GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); Gson gson = builder.create(); Movie movie = new Movie(null, 9.2, 1972); String jsonMovie = gson.toJson(movie); System.out.println(json);
Notice the call to serializeNulls()
on the GsonBuilder
instance before creating the Gson object. Once serializeNulls()
has been called the Gson instance created by the GsonBuilder
will include null
fields in the serialized JSON.
Custom serialization and deserialization
Gson offers the possibility for you to plug in customer serializers and deserializers. Your custom serializers can convert Java values to custom JSON, and your custom deserializers can convert custom JSON to Java values again.