RedEagle
RedEagle

Reputation: 4560

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?

Upvotes: 33

Views: 36766

Answers (4)

Nilu
Nilu

Reputation: 272

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);
}

Upvotes: 4

alexey28
alexey28

Reputation: 5220

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

Upvotes: 73

Neil C. Obremski
Neil C. Obremski

Reputation: 20244

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!

Upvotes: 2

slipset
slipset

Reputation: 3078

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

Upvotes: 4

Related Questions