33

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?

Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
RedEagle
  • 4,418
  • 9
  • 41
  • 64

4 Answers4

72

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);
Grant Foster
  • 722
  • 2
  • 11
  • 21
alexey28
  • 5,170
  • 1
  • 20
  • 25
4

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

slipset
  • 2,960
  • 2
  • 21
  • 17
4

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);
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Nilu
  • 262
  • 1
  • 8
2

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!

Neil C. Obremski
  • 18,696
  • 24
  • 83
  • 112