如何使用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。您可以从 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);
...