Gson - 从 Json 转换为类型化的 ArrayList<T> [英] Gson - convert from Json to a typed ArrayList<T>

查看:22
本文介绍了Gson - 从 Json 转换为类型化的 ArrayList<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Gson 库,如何将 JSON 字符串转换为自定义类 JsonLogArrayList?基本上,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.我该怎么办?

It seems the compiler doesn't understand I'm referring to a typed ArrayList. What do I do?

推荐答案

您可以使用 TypeToken 将 json 字符串加载到自定义对象中.

You may use TypeToken to load the json string into a custom object.

logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());

文档:

代表一个泛型类型T.

Java 还没有提供表示泛型类型的方法,所以这个类提供了.强制客户端创建此类的子类,即使在运行时也可以检索类型信息.

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.

例如,要为 List 创建类型字面量,您可以创建一个空的匿名内部类:

For example, to create a type literal for List<String>, you can create an empty anonymous inner class:

TypeToken>list = new TypeToken>() {};

此语法不能用于创建具有通配符参数的类型文字,例如 ClassList.

This syntax cannot be used to create type literals that have wildcard parameters, such as Class<?> or List<? extends CharSequence>.

科特林:

如果您需要在 Kotlin 中执行此操作,您可以这样做:

If you need to do it in Kotlin you can do it like this:

val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)

或者您可以查看此答案以了解各种替代方案.

Or you can see this answer for various alternatives.

这篇关于Gson - 从 Json 转换为类型化的 ArrayList&lt;T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆