在Java中序列化JSON字符串而不转义引号。

huangapple go评论71阅读模式
英文:

Serializing json string without escaping quote in java

问题

我有一个包含字符串列表 JSON 的字符串变量。我想将其作为值添加到映射中,以表示为字符串列表值。更具体地说:

String jsonListString = "[\"A\", \"B\"]";
Map<String, String> map = new HashMap();
map.put("KEY", jsonListString);

String serialized = new ObjectMapper().writeValueAsString(map);
System.out.println("Example:" + serialized);

输出如下:

Example:{"KEY":"[\"A\", \"B\"]"}

我期望的输出没有转义引号:

Example:{"KEY":["A", "B"]}
英文:

I have a string variable that contains json of list of strings. And I want to add this as a value to a map for representing as string list value. To be more specific:

String jsonListString = &quot;[\&quot;A\&quot;, \&quot;B\&quot;]&quot;;
Map&lt;String, String&gt; map = new HashMap();
map.put(&quot;KEY&quot;, jsonListString);


String serialized = new ObjectMapper().writeValueAsString(map);
System.out.println(&quot;Example:&quot; + serialized);

The output is the following:

Example:{&quot;KEY&quot;:&quot;[\&quot;A\&quot;, \&quot;B\&quot;]&quot;}

I'm expecting without escaping quotes

Example:{&quot;KEY&quot;:[&quot;A&quot;, &quot;B&quot;]}

答案1

得分: 1

目前您正在将一个字符串分配为KEY的值。如果您想改为分配一个数组,则它实际上需要是一个数组。

示例:

Map<String, String[]> map = new HashMap();
map.put("KEY", new String[]{"A", "B"});
英文:

Currently you are assigning a string as the value to KEY. If you want to assign an array instead it needs to actually be an array.

Ex

Map&lt;String, String[]&gt; map = new HashMap();
map.put(&quot;KEY&quot;, new String[]{&quot;A&quot;, &quot;B&quot;});

huangapple
  • 本文由 发表于 2020年9月5日 01:02:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63745305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定