RedEagle RedEagle - 1 month ago 9
Java Question

Gson Array of Strings to JsonArray

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?

Answer

You can create a primitive that will contains String value and add it to array:

JsonArray jArray = new JsonArray();
JsonPrimitive element = new JsonPrimitive("value1");
jArray.add(element);
Comments