我正在关注本教程,以便在 Windows Azure Mobile Android 中实现自定义序列化程序。我正在尝试使用代码,但是 E 变量出现错误。
public class CollectionSerializer implements JsonSerializer<Collection>, JsonDeserializer<Collection>{
public JsonElement serialize(Collection collection, Type type,
JsonSerializationContext context) {
JsonArray result = new JsonArray();
for(E item : collection){
result.add(context.serialize(item));
}
return new JsonPrimitive(result.toString());
}
@SuppressWarnings("unchecked")
public Collection deserialize(JsonElement element, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonArray items = (JsonArray) new JsonParser().parse(element.getAsString());
ParameterizedType deserializationCollection = ((ParameterizedType) type);
Type collectionItemType = deserializationCollection.getActualTypeArguments()[0];
Collection list = null;
try {
list = (Collection)((Class<?>) deserializationCollection.getRawType()).newInstance();
for(JsonElement e : items){
list.add((E)context.deserialize(e, collectionItemType));
}
} catch (InstantiationException e) {
throw new JsonParseException(e);
} catch (IllegalAccessException e) {
throw new JsonParseException(e);
}
return list;
}
}