8

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\"}"]}
vkislicins
  • 3,331
  • 3
  • 32
  • 62
  • Does [this](http://stackoverflow.com/questions/5813434/trouble-with-gson-serializing-an-arraylist-of-pojos) help you? quoting: "You need to give Gson information on the specific generic type of List you're using (or any generic type you use with it)." – Shervin Apr 14 '15 at 14:54
  • ```main.addProperty(KEY_ARRAY,gson.toJson(list,new TypeToken>(){}.getType()));``` unfortunately made no difference – vkislicins Apr 14 '15 at 23:33
  • Hmm... Actually it seems to me that the slashes are for escaping double quot character in the array values, since \" is the escape character for double quot in java and C. Basically if you print the value in the output, it should just be fine. check [this](http://stackoverflow.com/questions/7258858/gson-automatic-quote-escaping). – Shervin Apr 15 '15 at 02:51

1 Answers1

16

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"}]}
Alexis C.
  • 91,686
  • 21
  • 171
  • 177