![](/img/trans.png)
[英]How to write a custom serializer adapter for Gson that I can use with .NET?
[英]How should I pass this variable E to this class? Custom serializer GSON
我正在学习本教程,以便在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;
}
}
你可能想要像这样声明你的类:
public class CollectionSerializer<E> implements JsonSerializer<Collection<E>>,
JsonDeserializer<Collection<E>> {
第一种方法可以成为:
public JsonElement serialize(Collection<E> collection, Type type,
JsonSerializationContext context) {
JsonArray result = new JsonArray();
for(E item : collection){
result.add(context.serialize(item));
}
return new JsonPrimitive(result.toString());
}
或者,您可以保留类声明,并将方法更改为:
public <E> JsonElement serialize(Collection<E> collection, Type type,
JsonSerializationContext context) {
JsonArray result = new JsonArray();
for(E item : collection){
result.add(context.serialize(item));
}
return new JsonPrimitive(result.toString());
}
您需要哪一个取决于您的用例(给定的CollectionSerializer
是否总是期望相同类型的集合)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.