我正在嘗試創建一個通用類,以便與Google Gson一起使用。我創建了類GsonJsonConverterImplementation<T>
。這個類有以下方法:在Gson中使用通用類型
public T deserialize(String jsonString) {
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("MM/dd/yy HH:mm:ss");
Gson gson = builder.create();
return gson.fromJson(jsonString, T); // T.class etc. what goes here
}
的目標是,這種方法應該能夠一起工作任何類型的我已下定GsonJsonConverterImplementation的工作。不幸的是,gson.fromJson(jsonString, T)
不起作用,也沒有使用T.class
來代替T.我確信這個問題源於我對Java通用類型的理解不夠。與Gson一起使用泛型的正確方法是什麼?
編輯
使用Kris's answer我會認爲這應該工作。不幸的是,clazz不能以這種方式使用,並導致編譯器錯誤。與Gson一起使用集合和泛型類型有什麼選擇?
public List<T> deserializeList(String jsonString, Class<T> clazz) {
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("MM/dd/yy HH:mm:ss");
Gson gson = builder.create();
Type listType = new TypeToken<clazz>(){}.getType(); // compiler error
return gson.fromJson(jsonString, listType);
}
我不知道你是否可以使這個(名單 - 是好吧)與Gson一起工作,因爲TypeToken本質上仍然是一個靜態的c onstruct(這就是爲什麼你的代碼無法工作)。但是如果你不一定要使用Gson,Jackson確實支持類型的編程創建(通過TypeFactory方法),並允許你試圖實現的內容。 –
StaxMan
2011-03-22 19:26:59
Duplicate question:http://stackoverflow.com/questions/4226738/using-generics-with-gson?rq=1 – 2013-02-23 05:12:43