GSON - 转换JSON来一个类型的ArrayList< T> [英] Gson - convert from Json to a typed ArrayList<T>

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

问题描述

使用GSON库,我怎么转换的自定义类的JSON字符串到的ArrayList JsonLog ?基本上, JsonLog 是不同类型的日志我的Andr​​oid应用程序取得了实现的接口 - 短信记录,通话记录,数据记录 - 这的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屋!

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