java - Gson - 从 Json 转换为类型化的 ArrayList

使用 Gson 库,如何将 JSON 字符串转换为自定义类 JsonLogArrayList?基本上,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<?> or List<? 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/

相关文章:

json - 如何在构建 JSON 字符串时转义特殊字符?

php - 如何使用 PHP 从 JSON 中提取数据?

json - 如何修改新 PostgreSQL JSON 数据类型中的字段?

ajax - 将 .ajax() 与 JSONP 一起使用的基本示例?

jquery - 将数组传递给 $.ajax() 中的 ajax 请求

c# - 在 C# 中读取和解析 Json 文件

java - Java 中的 pretty-print JSON

javascript - 打印 JSON 解析的对象?

ruby - 'json' 原生 gem 需要安装构建工具

json - 如何在 Go 的 POST 请求中发送 JSON 字符串