I'm using Gson and am trying to add a bunch of string values into a JsonArray
like this:
JsonArray jArray = new JsonArray(); jArray.add("value1");
The problem is that the add method only takes a JsonElement
.
I've tried to cast a String into a JsonElement
but that didn't work.
How do I do it using Gson?
We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.
TypeToken; JsonElement yourJson = mapping. get("servers"); Type listType = new TypeToken<List<String>>() {}. getType(); List<String> yourList = new Gson().
JSON array of {object with an array of object}.Type listType = new TypeToken<List<Item>>() {}. getType(); List<Item> list = gson. fromJson(main. loadFileFromClasspath("array2.
You can create a primitive that will contain the String value and add it to the array:
JsonArray jArray = new JsonArray(); JsonPrimitive element = new JsonPrimitive("value1"); jArray.add(element);
Seems like you should make a new JsonPrimitive("value1")
and add that. See The javadoc
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