【发布时间】:2014-04-24 03:45:39
【问题描述】:
我的设置是这样的:
public enum AnimalType {
CAT(1),
DOG(2);
private final int value;
AnimalType(int value) {
this.value = value;
}
public int value() { return value; }
}
public class Dog {
AnimalType type = AnimalType.DOG;
String name;
int id;
//Other properties. Point is to distinguish it from a Cat object.
}
public class Cat {
AnimalType type = AnimalType.CAT;
String name;
String nickName;
int age;
}
public class Response {
ArrayList<Object> myResponseObject;
}
这是一个 Response 对象的外观示例:
ArrayList<Object> arr = new ArrayList<Object>();
Dog dog = new Dog("MyName",0);
Cat cat = new Cat("MyName","MyNickName",-1);
arr.add("I have a ");
arr.add(cat)
arr.add(" and a ");
arr.add(dog)
Response response = new Response(arr);
我是这样序列化的:
Gson gson = new Gson();
String serializedOutput = gson.toJson(response);
并希望像这样反序列化:
//the ArrayList<Object> should be populated correctly inside of it?
Response deserializedObject = gson.fromJson(serializedOutput);
但是,在反序列化此列表时,我需要将对象映射回它们各自的类型。我怀疑我至少需要将类或类型标记到我的 Dog 或 Cat 序列化中。现在,我在 Dog 和 Cat 上添加一个 Type 属性(而不是接口)。
没有任何花哨的东西,Cat 和Dog 对象在反序列化时默认被视为LinkedTreeMap<K,V>。我必须遍历我的arraylist,检查它是否是LinkedTreeMap 的实例,调用“type”键来获取类型,然后将我的对象转换为Dog 或Cat。这一切对我来说似乎有点老套,我想知道是否有更优雅的方法来做到这一点。
我应该为我的 Cat/Dog 对象使用自定义序列化器/反序列化器,还是应该使用 RuntimeTypeAdapterFactory?任何指导将不胜感激。
注意,我还按照Gson: How to change output of Enum 的指示自定义序列化/反序列化我的枚举。我不确定这是否会影响任何事情。
谢谢
【问题讨论】:
-
正如您在下面提到的,您要发布您的解决方案吗?
-
是的,我会的。抱歉耽搁了。一直很忙。我犹豫是否按原样处理它的原因是因为我的解决方案并不像我希望的那样干净。我不喜欢发布没有明确描述/解释 * 的答案。
-
我明白了。谢谢。