我正在编写一些用于从网站检索资源的代码。它看起来像这样:
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("foo@example.com", "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 内部的所有细节,而且我的搜索并没有提供特别丰富的信息。这里有很多关于 SO 的问题,但大多数都指的是实现方法,比如我原来的方法。GSON文档似乎没有涵盖这种特殊情况。再说一遍,如何使用 Google GSON 将 JSON 数组反序列化为泛型类型的集合?