This example will demonstrate how to convert a json array to a java ArrayList using gson JSON parser. In the set up, we will create a sample json array to represent navigation elements and a java object to unmarshall into java object named NavItem. This is the same class used in the example how to marshal a json array to an array list using jackson.
Setup
Sample json array
Sample java class
Serialization
Below we will serialize a java object into json using gson. We will initialize a java arraylist with two NavItems java objects by creating a Gson class from GSONBuilder class. The Gson class is the main class using Google Gson and can be built with various options. You will notice that we have commented out the ability to print json in a pretty format. Finally calling the toJson will serialize the navigation object into its equivalent Json representation.
Output
Deserialization
Converting from json to a java object or deserialization is a similar process. There is two subsnippets below. The first converts the json into an array of NavItems while the second deserializes a java generic type by specifying the correct parameterized type. You can do this by using the TypeToken class shown below.