Json array to ArrayList gson

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.


Sample json array

    "key":"Level up lunch",
    "key":"Java examples",
    "key":"Java exercises",
    "key":"Java tutorials",

Sample java class

class NavItem {

    private String linkText;
    private String url;



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.

public void convert_list_to_json() {

    NavItem item1 = new NavItem();

    NavItem item2 = new NavItem();

    List<NavItem> navigation = Lists.newArrayList(item1, item2);

    Gson gson = new GsonBuilder()
    // .setPrettyPrinting()

    String arrayListToJson = gson.toJson(navigation);


            + "{\"key\":\"exercises\",\"url\":\"http://leveluplunch.com/java/exercises\"}]",



    "key": "examples",
    "url": "http://leveluplunch.com/java/examples"
    "key": "exercises",
    "url": "http://leveluplunch.com/java/exercises"


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.

public void convert_json_to_array_or_list() {

    Gson gson = new Gson();

    NavItem[] navigationArray = gson.fromJson(jsonString, NavItem[].class);


    assertEquals(4, navigationArray.length);

    // or

    Type collectionType = new TypeToken<List<NavItem>>() {
    List<NavItem> navigation = gson.fromJson(jsonString, collectionType);


    assertEquals(4, navigation.size());


<[NavItem{key=Level up lunch, url=www.leveluplunch.com}, NavItem{key=Java examples, url=www.leveluplunch.com/java/examples/}, NavItem{key=Java exercises, url=www.leveluplunch.com/java/exercises/}, NavItem{key=Java tutorials, url=www.leveluplunch.com/java/tutorials/}]>