我是 JSON 和 GSON 的新手,我正在从输入流中获取 JSON 提要,并将其放入自定义对象的数组列表中。 JSON 源包含一个对象,该对象包含多个对象的数组。它看起来像这样:
{ "container":[
{"item_1":"item one"},
{"item_2":"item two"},
{"item_3":"item three"}
]}
我目前使用的是TypeToken
与 Map
获取容器对象以及对象列表作为自定义对象的数组列表。就像这样:
InputStreamReader input = new InputStreamReader(connection.getInputStream());
Type listType = new TypeToken<Map<String, ArrayList<Item>>>(){}.getType();
Gson gson = new GsonBuilder().create();
Map<String, ArrayList<Item>> treeMap = gson.fromJson(input, listType);
ArrayList<Item> objects = treeMap.get("container");
input.close();
我想知道是否有办法跳过创建Map<String, ArrayList<Item>>
的步骤,并直接从输入流转到 ArrayList<Item>
使用GSON。只是为了整合我的代码,创建 map 似乎是一个不必要的步骤。
最佳答案
一种选择是定义一个具有 container
属性的包装类型,然后将 JSON 反序列化为该类型而不是 Map
。
public static class Wrapper {
public List<Item> container;
}
Wrapper wrapper = gson.fromJson(input, Wrapper.class);
List<Item> objects = wrapper.container;
关于java - 使用 GSON 将包含数组的 JSON 对象转换为 ArrayList<POJO>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33437643/