I'm trying to build a JsonArray of JsonObjects using gson. Each JsonObject will take the following format,
{"image":"name1"}
{"image":"name2"}
and so on.
I have a string array of the names ("name1","name2",...) I cannot convert string array directly in to a JsonArray. I'm trying to create JsonObjects iteratively and add it to a JsonArray.
JsonObject innerObject;
JsonArray jArray = new JsonArray();
for(int i = 0; i<names.length; i++)
{
innerObject = new JsonObject();
innerObject.addProperty("image",names[i]);
jArray.add(innerObject);
}
But as I understand, add
method in JsonArray takes a JsonElement and here I'm giving a JsonObject. I couldn't find a way to convert JsonObject to JsonElement.
The whole point of using gson will be gone when I do this. Is there a better way?
JsonObject
extendsJsonElement
, so there's no reason you can't add one to aJsonArray
using theadd(JsonElement)
method. No conversion is required. – azurefrog Apr 14 '16 at 21:24