Abel Melquiades Callejo Abel Melquiades Callejo - 2 months ago 14
JSON Question

Parsing JSON array into java.util.List with Gson

I have a

JsonObject
named
"mapping"
with the following content:

{
"client": "127.0.0.1",
"servers": [
"8.8.8.8",
"8.8.4.4",
"156.154.70.1",
"156.154.71.1"
]
}


I know I can get the array
"servers"
with:

mapping.get("servers").getAsJsonArray()


And now I want to parse that
JsonArray
into a
java.util.List
...

What is the easiest way to do this?

Answer

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.