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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With