GSON Serialize and Deserialize Collections Example

GSON can serialize and Deserialize collections. In this example we serialize a collection of Integer into JSON representation and using the TypeToken to deserialize the collection of Integers into the arbitrary Java Object.

Serialize and Deserialize Collections

Gson gson = new GsonBuilder().create();
Collection integers = Arrays.asList(1, 2, 3);

// serialization
gson.toJson(integers);      // => [1,2,3]

// deserialization
Type collectionType = new TypeToken>(){}.getType();
Collection integers2 = gson.fromJson("[1,2,3]", collectionType);


GSON can serialize collections of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type. This makes sense, and is rarely a problem when following good java coding practices.

You may also like...