Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Real Collection Deserializer to parse arrays with GSON
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
* @param serializedData
* @param type
* @return
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
JsonElement json2 = (JsonElement);
T object = (T) gson.fromJson(json2, (Class<?>)type);
return newArray;
public class JSONParsingTest {
List<World> worlds;
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
public class World {
private String name;
private Long id;
public void setName(String name) { = name;
public String getName() {
return name;
public Long getId() {
return id;
public void setId(Long id) { = id;

amrafu commented May 29, 2013

Nice solution, I used it but I got error on:
public Collection<?> deserialize(JsonElement json, Type typeOfT,

The method deserialize(JsonElement, Type, JsonDeserializationContext) of type CollectionDeserializer must override a superclass method

Any idea?

Thanks in advance


miere commented Jul 24, 2013

Hi @amrafu
Sorry by the late, I missed up your answer notification.

Please, which version of GSon are you using?
I will try to simulate your problem to help you! ;)

Works great! Thanks! :-)

Thanks! Exactly what I'm looking for!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment