I'm using GSON library to create a json object and add a json array to it. My code looks something like this:
JsonObject main = new JsonObject();
main.addProperty(KEY_A, a);
main.addProperty(KEY_B, b);
Gson gson = new Gson();
ArrayList<JsonObject> list = new ArrayList<>();
JsonObject objectInList = new JsonObject();
objectInList.addProperty(KEY_C, c);
objectInList.addProperty(KEY_D, d);
objectInList.addProperty(KEY_E, e);
list.add(objectInList);
main.addProperty(KEY_ARRAY,gson.toJson(list));
The output seems to contain some unexpected slashes:
{"A":"a","B":"b","array":["{\"C\":\"c\",\"D\":\"d\",\"E\":\"e\"}"]}
When you do:
main.addProperty(KEY_ARRAY, gson.toJson(list));
you add a key-value pair String -> String
in your JsonObject
, not a String -> JsonArray[JsonObject]
.
Now you get this slashes because when Gson serialize this List into a String, it keeps the informations about the values in the json object in the array (that are Strings so the quotes need to be escaped via backslashes).
You could observe the same behavior by setting
Gson gson = new GsonBuilder().setPrettyPrinting().create();
then the output of the array is:
"array": "[\n {\n \"C\": \"c\",\n \"D\": \"d\",\n \"E\": \"e\"\n }\n]"
But what you are looking for is to have the correct mapping, you need to use the add
method and give a JsonArray
as parameter. So change your list
to be a JsonArray
:
JsonArray list = new JsonArray();
and use add
instead of addProperty
:
main.add("array", list);
and you'll get as output:
{"A":"a","B":"b","array":[{"C":"c","D":"d","E":"e"}]}
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