List of integers to JsonArray in GSON

arrays, gson, java, json

Solution

If you pass the list to the Gson#toJsonTree method, it returns a JsonArray.

List<Integer> list = new ArrayList<>();
list.add(5);
JsonElement result = new GsonBuilder().create().toJsonTree(list);
System.out.println(result.getClass()); // prints "class com.google.gson.JsonArray"

P.S.

In the code above, I create the Gson instance inline (new GsonBuilder().create()) for the sake of readability and copy-paste. In practice, you would most likely not create a new Gson instance every time you needed to convert a list, but rather, create an instance one time, earlier on, to be reused.

Problem

Right now my code is simply ``` // list is a List<Integer> JsonArray arr = new JsonArray(); for(int i : list) { array.add(i); } ``` I'm somewhat shocked looking through the API I haven't found a less manual, more functional way to do this. I would expect an `addRange`, `addArray`, constructor to go from a `Collection` to a `JsonArray`, etc. Is there one, or is there some fundamental limitation that makes this impossible?

Original source