Converting json (GSON) object to json array, put into list

3536 views java
4

My server returns JSON like this:

{
    "name": "test",
    "enabled": true
}

Which I read in as a string:

String json = <get server response here>;

// Get json as object
Group group = new Gson().fromJson(json, Group.class);

Instead, I want to convert the object to an array, so I get something like this instead:

[
    {
        "name": "group",
        "enabled": true
    }
]

And then get a list of the objects, like:

List<Group> groups = <something here, not sure what>;

How would this be done?

answered question

jsonarray or a normal array

@VishalSharma Json array

BTW, it literally says how to do lists in the Gson's Javadoc.

2 Answers

6

You can use an array of Group objects as the target type. Try this:

Group[] groups = new Gson().fromJson(json, Group[].class);

Gson (and Java in general) has issues with type erasure. That means that you can't pass the class of List<Group> to the method, just List.class. Therefore, it won't know that the elements of the list are supposed to be Group's. Using the array class will provide Gson everything it needs to convert them.

If you truly need the result as a List<Group>, you can use Arrays.asList:

Group[] array = new Gson().fromJson(json, Group[].class);
List<Group> groups = Arrays.asList(array);

posted this
12

You can use this approach to deserialize the json into a list:

List<Group> groups = gson.fromJson(json, new TypeToken<List<Group>>(){}.getType());

posted this

Have an answer?

JD

Please login first before posting an answer.