32
votes

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?

4

4 Answers

71
votes

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);
4
votes

Seems like you should make a new JsonPrimitive("value1") and add that. See The javadoc

4
votes

For newer versions of Gson library , now we can add Strings too. It has also extended support for adding Boolean, Character, Number etc. (see more here)

Using this works for me now:

JsonArray msisdnsArray = new JsonArray();
for (String msisdn : msisdns) {
    msisdnsArray.add(msisdn);
}
2
votes

I was hoping for something like this myself:

JsonObject jo = new JsonObject();
jo.addProperty("strings", new String[] { "value1", "value2" });

But unfortunately that isn't supported by GSON so I created this helper:

public static void Add(JsonObject jo, String property, String[] values) {
    JsonArray array = new JsonArray();
    for (String value : values) {
        array.add(new JsonPrimitive(value));
    }
    jo.add(property, array);
}

And then use it like so:

JsonObject jo = new JsonObject();
Add(jo, "strings", new String[] { "value1", "value2" });

Voila!