简体   繁体   English

我应该如何将此变量E传递给此类? 自定义序列化器GSON

[英]How should I pass this variable E to this class? Custom serializer GSON

I am following this tutorial in order to implement a custom serializer in Windows Azure Mobile Android. 我正在学习教程,以便在Windows Azure Mobile Android中实现自定义序列化程序。 I am trying to use the code however I am getting an error with E variable. 我试图使用代码但是我收到了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;
}
}

You possibly meant to declare your class like this: 你可能想要像这样声明你的类:

public class CollectionSerializer<E> implements JsonSerializer<Collection<E>>,
                                                JsonDeserializer<Collection<E>> {

The first method could then become: 第一种方法可以成为:

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());
}

Alternatively, you can leave the class declaration as is and change your method to: 或者,您可以保留类声明,并将方法更改为:

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());
}

Which one you need depends on your use case (whether a given CollectionSerializer always expects the same type of collection or not). 您需要哪一个取决于您的用例(给定的CollectionSerializer是否总是期望相同类型的集合)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM