3
在我的應用程序中,我使用的是ActiveAndoid
。
在某些型號中,我有一列List<String>
和其他List<MyEnum>
。
我創建了一個TypeSerializer
對於每種類型:
ActiveAndroid TypeSerializer - 枚舉列表
public class StringsListTypeSerializer extends TypeSerializer
{
private static GsonBuilder sGsonBuilder;
static{
sGsonBuilder = new GsonBuilder();
}
@Override
public Class<?> getDeserializedType() {
return List.class;
}
@Override
public Class<?> getSerializedType() {
return String.class;
}
@Override
public String serialize(Object data) {
if(data == null){
return null;
}
final Gson gson = sGsonBuilder.create();
return gson.toJson(data);
}
@Override
public List<String> deserialize(Object data) {
if(data == null){
return null;
}
final Gson gson = sGsonBuilder.create();
List<String> strings = gson.fromJson(data.toString(), List.class);
return strings;
}
}
和MyEnum
(這是一個enum
型):
public class MyEnumListTypeSerializer extends TypeSerializer {
private static GsonBuilder sGsonBuilder;
static{
sGsonBuilder = new GsonBuilder();
sGsonBuilder.registerTypeAdapter(MyEnum.class, new MyEnumJsonDeserializer());
}
@Override
public Class<?> getDeserializedType() {
return new TypeToken<ArrayList<MyEnum>>(){}.getType().getClass();
}
@Override
public Class<?> getSerializedType() {
return String.class;
}
@Override
public String serialize(Object data) {
if(data == null){
return null;
}
final Gson gson = sGsonBuilder.create();
return gson.toJson(data);
}
@Override
public ArrayList<MyEnum> deserialize(Object data) {
if(data == null){
return null;
}
final Gson gson = sGsonBuilder.create();
Type listType = new TypeToken<ArrayList<MyEnum>>(){}.getType();
ArrayList<MyEnum> myList = gson.fromJson(data.toString(), listType);
return myList;
}
}
我的問題是ActiveAndroid
序列化MyEnum
列表類型爲字符串的列表(與StringsListTypeSerializer
)和運行時,當我使用List<MyEnum>
爲每個循環我得到ClassCastException
- 不能投String
到Enum
。
如何解決這個問題?