34

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 Answers 4

74

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Why is this so ludicrously counterintuitive?
And why do the docs tell us there is a JsonArray.add(String)?!?
4

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

Comments

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

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.