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

使用Gson库创建JsonObject并添加JsonArray时遇到转义字符问题。当将ArrayList转化为Json时,输出的Json字符串包含意外的反斜杠。解决方法是将ArrayList转换为JsonArray,并使用JsonObject的`add`方法添加JsonArray,而不是`addProperty`,以避免字符串化导致的转义。
摘要由CSDN通过智能技术生成

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值