我正在写一些将用于从网站检索资源的代码。它看起来像这样:如何使用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