tyrondis
tyrondis

Reputation: 3494

GSON to serialize/deserialize to/from a custom generic collection type

I am looking for a way to configure GSON to serialize to and deserialize from a custom generic collection type.

The collection in question is LibGDX' Array type.

I am unable to find documentation of how to achieve this. Can anyone help?

Upvotes: 0

Views: 2135

Answers (1)

pr0gramista
pr0gramista

Reputation: 9008

Solution 1:

Converting into standard Java array. Since Array is actually just a wrapper around standard Java array we won't lose data converting it and Gson can easily handle serializing and deserializing standard arrays for us.

Array<Human> array = new Array<Human>();
array.add(new Human("Jack"));
array.add(new Human("Tom"));
array.add(new Human("Mel"));
array.add(new Human("Anne"));

Gdx.app.log("JSON", "To json");
for (Human human : array) {
    Gdx.app.log("Human", human.name);
}

Gson gson = new Gson();
String json = gson.toJson(array.toArray(), Human[].class);
Array<Human> arrayFromJson = new Array<Human>(gson.fromJson(json, Human[].class));

Gdx.app.log("JSON", "From json");
for (Human human : arrayFromJson) {
    Gdx.app.log("Human", human.name);
}

Output:

JSON: To json
Human: Jack
Human: Tom
Human: Mel
Human: Anne
JSON: From json
Human: Jack
Human: Tom
Human: Mel
Human: Anne

Solution 2:

If you had Array<Human> in some kind of object you would need to manually convert from Java array to LibGDX array, which will be a little bit messy.

Writing own serializers is solution to this, but writing serializers with generics is complicated, but possible.

The hardest part is deserializer:

public class ArrayDeserializer<T> implements JsonDeserializer<Array<T>> {
    Class<T[]> tClass;

    public ArrayDeserializer(Class<T[]> tClass) {
        this.tClass = tClass;
    }

    @Override
    public Array<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        T[] objects = context.deserialize(json, tClass);
        return new Array<T>(objects);
    }
}

Serializer is pretty dumb.

public class ArraySerializer implements JsonSerializer<Array> {
    @Override
    public JsonElement serialize(Array src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(src.toArray(), src.toArray().getClass());
    }
}

And then used in code:

Type type = TypeToken.get(array.getClass()).getType(); //Array<Human>
...
gsonBuilder.registerTypeAdapter(type, new ArrayDeserializer<Human>(Human[].class));
gsonBuilder.registerTypeAdapter(type, new ArraySerializer());

Then you build new Gson instance that is capable of serializing libGDX's Array.

Upvotes: 2

Related Questions