Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of integers to JsonArray in GSON

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?

like image 993
djechlin Avatar asked Feb 24 '14 16:02

djechlin


People also ask

What does JSONArray contain?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

How get values from JSONArray?

You can get the value using the line: String value = (String) getKey(array, "key1") . We cast to a string because we know "key1" refers to a string object.

How do I create a JSONArray?

A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object. JsonArray value = Json. createArrayBuilder() . add(Json.


Video Answer


1 Answers

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.

like image 97
Michael Bosworth Avatar answered Sep 23 '22 05:09

Michael Bosworth