2013-08-27 19 views
0

我正在關注this教程,以便在Windows Azure Mobile Android中實現自定義序列化器。我試圖使用代碼,但我得到一個E變量的錯誤。我應該如何將這個變量E傳遞給這個類?自定義序列化器GSON

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; 
} 
} 
+0

你得到了什麼錯誤? –

+0

無法解析符號'E' –

+0

當然,您還沒有在方法中聲明任何類型參數。該方法不是通用的。所以'E'不能解決。你爲什麼要強調「E」? –

回答

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

相關問題