如何使用GSON解析并放入对象列表? [英] How can I use GSON to parse and place into a list of objects?

查看:127
本文介绍了如何使用GSON解析并放入对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个域对象Foo,我想解析一些JSON,例如

I have a domain object Foo, and I want to parse some JSON such as

[
    {"prop": "val"},
    {"prop": "val2"},
]

我想得到一个List<Foo>.像这样

List<Foo> foos = new Gson().fromJson(json, /*what goes here ?*/);

推荐答案

您需要使用TypeToken正确表示类型.在这种情况下,Class是不够的,因为与泛型类型有相互作用.

You need to use a TypeToken to correctly express the type. Class is not sufficient in this case, because of the interaction with the generic type.

Type listType = new TypeToken<List<Foo>>(){}.getType();
List<Foo> projects = (List<Foo>) gson.fromJson(response, listType);

这篇关于如何使用GSON解析并放入对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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