Creating JSON document using Java and GSON API

We saw how to parse JSON using GSON API, in this post we would take a look at how the same GSON API can be used to create JSON from the Java objects. Please read this to get an idea of what GSON is. Diving right into the topic of this example, we would make use of the toJson method of com.google.gson.Gson class. One of the overloaded versions of toJson() takes in an source of type Object and the type information which is of class java.lang.reflect.Type.

We populate a list with some values for this model bean and this list would be converted to JSON output. Note the use of @SerializedName annotation in the model class. This indicates the name used for the attribute in the json output. We populate the list of books using:

Once we have a list, we need to serialize it to JSON, for that we need to setup a Type information for generic List, this is not possible out of the box in Java and hence we would make use of com.google.gson.reflect.TypeToken class in the GSON API, to create the type information like:

// Get the type information for the List<Book>
Type listType = new TypeToken<List<Book>>(){}.getType();

Next up is to use this type information along with the list of books and pass it to the toJson method to obtain the JSON output.