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

Nas*_*qan 16 java json gson

我想使用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"}
]
Run Code Online (Sandbox Code Playgroud)

我从PHP脚本中获取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"}
]
Run Code Online (Sandbox Code Playgroud)

Kir*_*ein 47

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

@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);
}
Run Code Online (Sandbox Code Playgroud)

如果您有JSONArray,那么您可以使用

...
JSONArray jsonArray = ...
gson.fromJson(jsonArray.toString(), listType);
...
Run Code Online (Sandbox Code Playgroud)

  • FYI,对于Type是java.lang.reflect.Type.有百万种类型,所以自动完成可能会令人困惑. (3认同)