我想使用Gson反序列化一个
JSON数组.我试图这样做,但我不能这样做.
JSON数组:
[
{"ID":1,"Title":"Lion","Description":"bla bla","ImageURL":"http:\/\/localhost\/lion.jpg"},{"ID":1,"Title":"Tiger","ImageURL":"http:\/\/localhost\/tiger.jpg"}
]
我从PHP脚本获取JSON数组:
$array = array (
array ( 'ID' => 1,'Title' => 'Lion','Description' => 'bla bla','ImageURL' => 'http:\/\/localhost\/lion.jpg' ),array ( 'ID' => 2,'Title' => 'Tiger','ImageURL' => 'http:\/\/localhost\/tiger.jpg' ),);
echo json_encode ($array);
解决方法
要反序列化JSONArray,您需要使用Typetoken.您可以从
GSON user guide阅读更多信息.示例代码:
@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,那么你可以使用
... JSONArray jsonArray = ... gson.fromJson(jsonArray.toString(),listType); ...