javajsonparsinggson

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?


Solution

  • 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;
    
    JsonElement yourJson = mapping.get("servers");
    Type listType = new TypeToken<List<String>>() {}.getType();
    
    List<String> yourList = new Gson().fromJson(yourJson, listType);
    

    In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

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