Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use GSON to parse and place into a list of objects?

Tags:

java

gson

I have a domain object Foo, and I want to parse some JSON such as

[
    {"prop": "val"},
    {"prop": "val2"},
]

I want to get a List<Foo>. Something like this

List<Foo> foos = new Gson().fromJson(json, /*what goes here ?*/);
like image 715
Adam Avatar asked Oct 28 '11 01:10

Adam


People also ask

What does Gson toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

You need to use a TypeToken to correctly express the type. Class is not sufficient in this case, because of the interaction with the generic type.

Type listType = new TypeToken<List<Foo>>(){}.getType();
List<Foo> projects = (List<Foo>) gson.fromJson(response, listType);
like image 183
yorkw Avatar answered Oct 13 '22 06:10

yorkw