2012-02-16 93 views
0

我正在使用返回JSON的服務,該服務可以轉換爲Map(我正在使用google-gson lib進行轉換)。我需要從該地圖獲取一組值。 首先,我有一個結構:使用泛型的調用方法

public Set<ProfileShow> getShows() { 
    String json = ...; //getting JSON from service 
    if (!Utils.isEmptyString(json)) { 
     Map<String, ProfileShow> map = Utils.fromJSON(json, new TypeToken<Map<String, ProfileShow>>() { 
     }.getType()); 

     Set<ProfileShow> result = new HashSet<ProfileShow>(); 
     for (String key : map.keySet()) { 
     result.add(map.get(key)); 
     } 
     return result; 
    } 
    return Collections.emptySet(); 
} 

public Set<Episode> getUnwatchedEpisodes() { 
    String json = ...; //getting JSON from service 
    if (!Utils.isEmptyString(json)) { 
     Map<String, Episode> map = Utils.fromJSON(json, new TypeToken<Map<String, Episode>>() { 
     }.getType()); 

     Set<Episode> result = new HashSet<Episode>(); 
     for (String key : map.keySet()) { 
     result.add(map.get(key)); 
     } 
     return result; 
    } 
    return Collections.emptySet(); 
} 

Utils.fromJSON方法:

public static <T> T fromJSON(String json, Type type) { 
    return new Gson().fromJson(json, type); 
} 

正如你所看到的,方法getShows()和getUnwatchedEpisodes()具有相同的結構。唯一的區別是返回Set的參數化類型。所以,我決定搬到得到設定從JSON到util的方法:

public static <T> Set<T> setFromJSON(String json, T type) { 
    if (!isEmptyString(json)) { 
     Map<String, T> map = fromJSON(json, new TypeToken<Map<String, T>>() { 
     }.getType()); 

     Set<T> result = new HashSet<T>(); 
     for (String key : map.keySet()) { 
     result.add(map.get(key)); 
     } 
     return result; 
    } 
    return Collections.emptySet(); 
} 

但現在我卡住瞭如何調用有道此方法。類似於

Utils.setFromJSON(json, Episode.class.getGenericSuperclass()); //doesn't work 

感謝您的幫助。

回答

1

也許最簡單的做法是將type的類型更改爲Type,並通過new TypeToken<Map<String, ProfileShow>>() { }.getType()或類似的。

我想你可以構造ParameterizedType,如果你真的想。