java 将 JsonArray 添加到 JsonObject 生成的转义字符 (gson)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29628853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:37:58  来源:igfitidea点击:

Adding JsonArray to JsonObject generated escape characters (gson)

javaandroidjsongson

提问by vkislicins

I'm using GSONlibrary to create a json object and add a json array to it. My code looks something like this:

我正在使用GSON库创建一个 json 对象并向其添加一个 json 数组。我的代码看起来像这样:

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\"}"]}

回答by Alexis C.

When you do:

当你这样做时:

main.addProperty(KEY_ARRAY, gson.toJson(list));

you add a key-value pair String -> Stringin your JsonObject, not a String -> JsonArray[JsonObject].

您添加一个键值对String -> String你的JsonObject,而不是一个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 序列化为一个字符串时,它会在数组中保留有关 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 addmethod and give a JsonArrayas parameter. So change your listto be a JsonArray:

但是你要找的是有正确的映射,你需要使用该add方法并给出一个JsonArray作为参数。所以改变你list是一个JsonArray

JsonArray list = new JsonArray();

and use addinstead of addProperty:

并使用add代替addProperty

main.add("array", list);

main.add("array", list);

and you'll get as output:

你会得到作为输出:

{"A":"a","B":"b","array":[{"C":"c","D":"d","E":"e"}]}