[英]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. 我正在使用GSON库来创建一个json对象并向其添加一个json数组。 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]
. 你在你的
JsonObject
添加一个键值对String -> String
,而不是一个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). 现在你得到这个斜杠,因为当Gson将这个List序列化为一个String时,它会保留数组中json对象中值的信息(即字符串,因此引号需要通过反斜杠进行转义)。
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. 但是你要找的是拥有正确的映射,你需要使用
add
方法并将JsonArray
作为参数。 So change your list
to be a JsonArray
: 所以将
list
更改为JsonArray
:
JsonArray list = new JsonArray();
and use add
instead of addProperty
: 并使用
add
而不是addProperty
:
main.add("array", list);
and you'll get as output: 你会得到输出:
{"A":"a","B":"b","array":[{"C":"c","D":"d","E":"e"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.