简体   繁体   中英

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. I am trying to use the code however I am getting an error with E variable.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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