如何避免返回JSON字符串列表的响应中的转义字符?

您所在的位置:网站首页 亮度250cdm2 如何避免返回JSON字符串列表的响应中的转义字符?

如何避免返回JSON字符串列表的响应中的转义字符?

#如何避免返回JSON字符串列表的响应中的转义字符?| 来源: 网络整理| 查看: 265

用例:从Spring控制器返回一个JSON列表( JSON字符串来自第三方库)。

Problem:REST控制器的响应具有转义字符。只有当返回类型是列表或数组或任何其他集合类型时,才会发生这种情况。返回单个字符串很好。

如何返回JSON格式字符串的列表,但避免转义字符。

import java.util.Arrays; import java.util.List; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("restjson") public class RestJsonController { @GetMapping(value="list", produces = {MediaType.APPLICATION_JSON_VALUE}) public List getValues(){ String value1 = "{\"name\":\"John\", \"age\":30}"; String value2 = "{\"name\":\"Tom\", \"age\":21}"; return Arrays.asList(value1, value2); //response has escape characters: //["{\"name\":\"John\", \"age\":30}","{\"name\":\"Tom\", \"age\":21}"] } @GetMapping(value="single", produces = {MediaType.APPLICATION_JSON_VALUE}) public String getValue(){ String value1 = "{\"name\":\"John\", \"age\":30}"; String value2 = "{\"name\":\"Tom\", \"age\":21}"; return value1.concat(value2); //response has no escape characters: //{"name":"John", "age":30}{"name":"Tom", "age":21} } }

Springboot版本: 2.7.0

完整代码:https://github.com/rai-sandeep/restjson/blob/main/src/main/java/com/sdprai/restjson/controller/RestJsonController.java

编辑

为了避免与字符串连接相关的任何混淆,我已经更新了代码(见下文)。即使只有一个JSON字符串,返回一个列表也会导致响应中的转义字符。但是只返回一个字符串就没有这个问题了。我不明白这种差异背后的原因。对于我的用例,是否有一种方法可以返回不带转义字符的JSON字符串列表?

import java.util.Collections; import java.util.List; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("restjson") public class RestJsonController { @GetMapping(value="list", produces = {MediaType.APPLICATION_JSON_VALUE}) public List getValues(){ String value1 = "{\"name\":\"John\", \"age\":30}"; return Collections.singletonList(value1); //returns: ["{\"name\":\"John\", \"age\":30}"] } @GetMapping(value="single", produces = {MediaType.APPLICATION_JSON_VALUE}) public String getValue(){ String value1 = "{\"name\":\"John\", \"age\":30}"; return value1; //returns: {"name":"John", "age":30} } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3