[英]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. 我正在寻找一种配置GSON以便从定制的通用集合类型序列化和反序列化的方法。
The collection in question is LibGDX' Array type. 有问题的集合是LibGDX'数组类型。
I am unable to find documentation of how to achieve this. 我找不到有关如何实现此目的的文档。 Can anyone help?
有人可以帮忙吗?
Solution 1: 解决方案1:
Converting into standard Java array. 转换为标准Java数组。 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实际上只是标准Java数组的包装器,因此我们不会丢失对其进行转换的数据,Gson可以轻松地为我们处理标准数组的序列化和反序列化。
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: 解决方案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. 如果您在某种对象中具有
Array<Human>
,则需要从Java数组手动转换为LibGDX数组,这会有些混乱。
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. 然后,构建新的Gson实例,该实例能够序列化libGDX的Array。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.