使用 Gson 库,如何将 JSON 字符串转换为自定义类 JsonLog
的 ArrayList
?基本上,JsonLog
是由我的 Android 应用程序生成的不同类型的日志实现的接口(interface)——SMS 日志、通话日志、数据日志——而这个 ArrayList
是一个集合他们全部。我在第 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
。我该怎么办?
最佳答案
您可以使用 TypeToken将 json 字符串加载到自定义对象中。
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
文档:
Represents a generic type T.
Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
For example, to create a type literal for
List<String>
, you can create an empty anonymous inner class:
TypeToken<List<String>> list = new TypeToken<List<String>>() {};
This syntax cannot be used to create type literals that have wildcard parameters, such as
Class<?>
orList<? extends CharSequence>
.
Kotlin :
如果你需要在 Kotlin 中这样做,你可以这样做:
val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)
或者你可以看this answer各种替代品。
关于java - Gson - 从 Json 转换为类型化的 ArrayList<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384064/