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#.
JsonPrimitive. You should be able to use array.add(new JsonPrimitive(yourString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With