Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JsonArray to JsonObject generated escape characters (gson)

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\"}"]}
like image 372
vkislicins Avatar asked Apr 14 '15 13:04

vkislicins


1 Answers

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"}]}
like image 164
Alexis C. Avatar answered Sep 20 '22 05:09

Alexis C.