如何使用Gson库反序列化对象的JSON数组?

问题描述 投票:16回答:1

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

JSON数组的示例:

[
    {"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代码是什么?

java json gson
1个回答
46
投票

要反序列化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);
...
© www.soinside.com 2019 - 2024. All rights reserved.