【问题标题】:How should I pass this variable E to this class? Custom serializer GSON我应该如何将这个变量 E 传递给这个类?自定义序列化器 GSON
【发布时间】:2013-08-27 21:34:31
【问题描述】:

我正在关注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;
}
}

【问题讨论】:

  • 你遇到了什么错误?
  • 无法解析符号“E”
  • 当然你没有在你的方法中声明任何类型参数。该方法不是通用的。所以,E 无法解决。你为什么要转换成E
  • 因为我不确定要传递的集合的类型。
  • 我是 Java 新手,所以我不确定是否应该这样做。我将在没有类型转换的情况下尝试它,看看它是否有效。

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


【解决方案1】:

你可能打算这样声明你的类:

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

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多