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

时间:2013-08-27 21:34:32

标签: java generics serialization gson azure-mobile-services

我正在关注this教程,以便在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;
}
}

1 个答案:

答案 0 :(得分:2)

你可能想要宣布你的课程如下:

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是否总是期望相同类型的集合。)