4

I am using gson to create JSON objects in Java. I am trying to make an array with three elements:

[ "ONE", "TWO", "THREE" ]

With this code:

    JsonArray   array   = new JsonArray ();
    array.add("ONE");
    array.add("TWO");
    array.add("THREE");

But the add() only accepts a JsonElement object, rather than an actual string.


The reason I'm under the impression I should be able to do this, is because I've used a C# script called SimpleJSON with Unity3D in the past. With it, I could do this:

    JSONArray ary = new JSONArray ();
    ary.Add("ONE");
    ary.Add("TWO");
    ary.Add("THREE");

Which works fine. I'm just not sure how to do this with gson.


I know I can convert a Java array into a JSON object:

String[] strings = {"abc", "def", "ghi"};
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

However, I want to dynamically createobjects in a JsonArray (the Add method), like I can with C#.

0

4 Answers 4

4

JsonPrimitive. You should be able to use array.add(new JsonPrimitive(yourString);

Sign up to request clarification or add additional context in comments.

Comments

1

You could do something like:

JsonArray array = new JsonArray();
array.add(new JsonPrimitive("ONE"));
array.add(new JsonPrimitive("TWO"));
array.add(new JsonPrimitive("THREE"));

Comments

1

There's an alternative to do that with Lists, which are really easy to manipulate.
You can add your Strings to a List and then create a JSON from it:

List<String> list = new ArrayList<String>();
list.add("ONE");
list.add("TWO");
list.add("THREE");

Gson gson = new Gson();
String array = gson.toJson(list);

Comments

1

array.add(gson.toJsonTree ("ONE"));

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.