如何使用Gson反序列化JSON数组

如何使用Gson反序列化JSON数组

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

问题描述

我想用Gson反序列化一个JSON数组。我试图这样做,但我做不到。

I want to deserialize a JSON array using Gson. I tried to do that but I couldn't do it.

JSON数组:

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"}
]

我从PHP获取JSON数组脚本:

I get the JSON array from a PHP script:

$array = array (
    array ( 'ID' => 1 , 'Title' => 'Lion' , 'Description' => 'bla bla' , 'ImageURL' => 'http:\/\/localhost\/lion.jpg' ) ,
    array ( 'ID' => 2 , 'Title' => 'Tiger' , 'Description' => 'bla bla' , 'ImageURL' => 'http:\/\/localhost\/tiger.jpg' ) ,
);
echo json_encode ($array);


推荐答案

要反序列化JSONArray,您需要使用TypeToken。您可以从了解更多信息。示例代码:

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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:24