简体   繁体   English

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

[英]How to deserialize a JSON array of objects using Gson library?

I am facing an issue while I am trying to deserialize a JSON array of objects using the Gson library.我在尝试使用 Gson 库反序列化 JSON 对象数组时遇到问题。

An example of the JSON array: 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"}
]

What do you think?你怎么认为? What is the proper Java code to deserialize such a JSON response?反序列化这样的 JSON 响应的正确 Java 代码是什么?

To deserialize a JSONArray you need to use TypeToken. 要反序列化JSONArray,您需要使用TypeToken。 You can read more about it from GSON user guide . 您可以从GSON用户指南中了解更多信息。 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);
}

If you have a JSONArray then you can use 如果您有JSONArray,则可以使用

...
JSONArray jsonArray = ...
gson.fromJson(jsonArray.toString(), listType);
...

For example your service has such response例如你的服务有这样的回应

[ new SomeObject(), new SomeObject(), new SomeObject() ] - this is jsonArray [ new SomeObject(), new SomeObject(), new SomeObject() ] - 这是 jsonArray

SomeObject - is a class instance of that your array is contains. SomeObject - 是您的数组包含的 class 实例。

You should use special class TypeToken (docs here https://sites.google.com/site/gson/gson-user-guide )您应该使用特殊的 class TypeToken(文档在这里https://sites.google.com/site/gson/gson-user-guide

Type type = new TypeToken<List<SomeObject>>(){}.getType();



String jsonArray = restResponse.getPayload(); - you get response as String
List<SomeObject > list = new Gson().fromJson(jsonArray, type);

Done!完毕!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM