0

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. The JSON feed contains a single object, which contains an array of more objects. 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. 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. Just to consolidate my code, creating a map seems like an unnecessary step.

1 Answer 1

1

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.

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

Wrapper wrapper = gson.fromJson(input, Wrapper.class);
List<Item> objects = wrapper.container;
Sign up to request clarification or add additional context in comments.

1 Comment

Would this approach be any more efficient? It essentially gets rid of the need for a TypeToken, but you need to create another class. It looks like a good alternative, but not exactly what I was hoping for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.