GSON - 转换JSON来一个类型的ArrayList&LT; T&GT; [英] Gson - convert from Json to a typed ArrayList<T>
问题描述
使用GSON库,我怎么转换的自定义类的JSON字符串到的ArrayList
JsonLog
?基本上, JsonLog
是不同类型的日志我的Android应用程序取得了实现的接口 - 短信记录,通话记录,数据记录 - 这的ArrayList
是所有的人的集合。我不断收到在第6行的错误。
Using the Gson library, how do I convert a JSON string to an ArrayList
of a custom class JsonLog
? Basically, JsonLog
is an interface implemented by different kinds of logs made by my Android app--SMS logs, call logs, data logs--and this ArrayList
is a collection of all of them. I keep getting an error in line 6.
public static void log(File destination, JsonLog log) {
Collection<JsonLog> logs = null;
if (destination.exists()) {
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(destination));
logs = gson.fromJson(br, ArrayList<JsonLog>.class); // line 6
// logs.add(log);
// serialize "logs" again
}
}
这似乎编译器不明白我指的是类型化的的ArrayList
。我该怎么办?
推荐答案
您可以使用<一个href="http://google-gson.google$c$c.com/svn/tags/1.1.1/docs/javadocs/com/google/gson/reflect/TypeToken.html">TypeToken加载JSON字符串转换成自定义对象。
You may use TypeToken to load the json string into a custom object.
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
这篇关于GSON - 转换JSON来一个类型的ArrayList&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!