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 ?*/);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With