简体   繁体   English

包含数组的JSON对象到ArrayList <POJO> 与GSON

[英]JSON Object Containing Array To ArrayList<POJO> With GSON

I am new to JSON and GSON, and I am taking a JSON feed from an input stream, and put it into an array list of custom objects. 我是JSON和GSON的新手,我从输入流中获取JSON提要,并将其放入自定义对象的数组列表中。 The JSON feed contains a single object, which contains an array of more objects. JSON提要包含一个对象,其中包含更多对象的数组。 It looks something like this: 看起来像这样:

{ "container":[
    {"item_1":"item one"},
    {"item_2":"item two"},
    {"item_3":"item three"}
]}

I am currently using a TypeToken with a Map to obtain the container object along with the list of objects as an array list of custom objects. 我目前正在将TypeTokenMap一起使用,以获取容器对象以及对象列表,作为自定义对象的数组列表。 Like so: 像这样:

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();

I would like to know if there is a way to skip the step of creating a Map<String, ArrayList<Item>> , and go directly from the input stream to an ArrayList<Item> using GSON. 我想知道是否有一种方法可以跳过创建Map<String, ArrayList<Item>> ,并使用GSON直接从输入流转到ArrayList<Item> Just to consolidate my code, creating a map seems like an unnecessary step. 只是为了合并我的代码,创建地图似乎是不必要的步骤。

One option is to define a wrapper type which has a container property, and then deserialize the JSON to that type instead of to a Map . 一种选择是定义一个具有container属性的包装器类型,然后将JSON反序列化为该类型,而不是Map

public static class Wrapper {
    public List<Item> container;
}

Wrapper wrapper = gson.fromJson(input, Wrapper.class);
List<Item> objects = wrapper.container;

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

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