Abel Melquiades Callejo Abel Melquiades Callejo - 10 months ago 50
JSON Question

Parsing JSON array into java.util.List with Gson

I have a

with the following content:

"client": "",
"servers": [

I know I can get the array


And now I want to parse that
into a

What is the easiest way to do this?

Answer Source

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
// ...
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(mapping.get("servers"), listType);

You may want to take a look at Gson API documentation.