Creating an array with Gson

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

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

      

With this code:

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

      

But it add()

accepts an object JsonElement

, not an actual string.


The reason I am impressed I have to do this is because I have used a C # script called SimpleJSON with Unity3D in the past. With this, I could do this:

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

      

Which works great. I just don't know how to do this with gson.


I know I can convert a Java array to an object JSON

:

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

      

However, I want to dynamically create objects in JsonArray

(method Add

) as I can with C #.

+3


source to share


4 answers


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



+4


source


There is an alternative to do this with List s, which are very easy to manipulate.
You can add String to List and then create 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);

      

+1


source


You can do something like:

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

      

+1


source


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

+1


source







All Articles