我正在寫一些將用於從網站檢索資源的代碼。它看起來像這樣:如何使用Google GSON將JSON數組反序列化爲泛型類型的集合?
public Collection<Project> getProjects() {
String json = getJsonData(methods.get(Project.class)); //Gets a json list, ie [1, 2, 3, 4]
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Project>>() {}.getType();
return gson.fromJson(json, collectionType);
}
所以自然我試着用Java泛型來抽象它。
/*
* Deserialize a json list and return a collection of the given type.
*
* Example usage: getData(AccountQuota.class) -> Collection<AccountQuota>
*/
@SuppressWarnings("unchecked")
public <T> Collection<T> getData(Class<T> cls) {
String json = getJsonData(methods.get(cls)); //Gets a json list, ie [1, 2, 3, 4]
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<T>>(){}.getType();
return (Collection<T>) gson.fromJson(json, collectionType);
}
雖然代碼的通用版本不起作用。
public void testGetItemFromGetData() throws UserLoginError, ServerLoginError {
Map<String,String> userData = GobblerAuthenticator.authenticate("[email protected]", "mypassword");
String client_key = userData.get("client_key");
GobblerClient gobblerClient = new GobblerClient(client_key);
ArrayList<Project> machines = new ArrayList<Project>();
machines.addAll(gobblerClient.getData(Project.class));
assertTrue(machines.get(0).getClass() == Project.class);
Log.i("Machine", gobblerClient.getData(Project.class).toString());
}
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.gobbler.synchronization.Machine
at com.gobblertest.GobblerClientTest.testGetItemFromGetData(GobblerClientTest.java:53)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:545)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)
類問題:
import java.util.Map;
public class Project {
private int total_bytes_stored;
private String name;
private String user_data_guid;
private int seqnum;
private String guid;
private Map current_checkpoint;
private Map<String, String> upload_folder;
// TODO: schema_version
private boolean deleted;
// TODO: download_folders
public Project() {} // No args constructor used for GSON
}
我不是很熟悉Java泛型或GSON內部的所有細節,我的搜索一直沒有特別的信息。在這裏有很多問題,但大多數都提到了像我原來那樣的實現方法。而GSON docs似乎不包括這個特殊情況。那麼,我又如何使用Google GSON將JSON數組反序列化爲一個泛型類型的集合呢?
很好聽,如果只給關閉。我理解這個話題可能有點牽扯,但你能解釋一下爲什麼簡單嗎? – 2012-04-28 06:02:30
爲了向後兼容和實現簡單,JVM在運行時不知道類型參數的類型。通常你不在乎,但這是你做的一種情況。網絡上有很多關於「Java擦除」的文章,有更多的細節。 – 2012-04-29 22:09:32
其實你可以檢查@jevon給出的答案http://stackoverflow.com/a/12576189/608805 – raukodraug 2014-09-09 21:57:55