如何使用Gson库反序列化对象的JSON数组? [英] How to deserialize a JSON array of objects using Gson library?

查看:105
本文介绍了如何使用Gson库反序列化对象的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用Gson库反序列化对象的JSON数组时遇到问题.

I am facing an issue while I am trying to deserialize a JSON array of objects using the Gson library.

JSON数组的示例:

An example of the JSON array:

[
    {"ID":1,"Title":"Lion","Description":"bla bla","ImageURL":"http:\/\/localhost\/lion.jpg"},
    {"ID":1,"Title":"Tiger","Description":"bla bla","ImageURL":"http:\/\/localhost\/tiger.jpg"}
]

您怎么看?反序列化此类JSON响应的正确Java代码是什么?

What do you think? What is the proper Java code to deserialize such a JSON response?

推荐答案

要反序列化JSONArray,您需要使用TypeToken.您可以从 GSON用户指南中了解更多信息.示例代码:

To deserialize a JSONArray you need to use TypeToken. You can read more about it from GSON user guide. Example code:

@Test
public void JSON() {
    Gson gson = new Gson();
    Type listType = new TypeToken<List<MyObject>>(){}.getType();
    // In this test code i just shove the JSON here as string.
    List<Asd> asd = gson.fromJson("[{'name':\"test1\"}, {'name':\"test2\"}]", listType);
}

如果您有JSONArray,则可以使用

If you have a JSONArray then you can use

...
JSONArray jsonArray = ...
gson.fromJson(jsonArray.toString(), listType);
...

这篇关于如何使用Gson库反序列化对象的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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