Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array with Gson

Tags:

java

json

gson

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#.

like image 209
Voldemort Avatar asked Oct 23 '25 19:10

Voldemort


1 Answers

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

like image 164
scrappedcola Avatar answered Oct 26 '25 08:10

scrappedcola