【问题标题】:Avoid JSON escape in the response避免响应中的 JSON 转义
【发布时间】:2018-09-12 02:57:23
【问题描述】:

我有一个 springboot 应用程序得到了一定的响应

除了responseStr 的格式之外,一切正常

它像 "responseStr":"{\"version\":\"1243423as2\",\"location\":\"Americas\"}"一样打印

我希望它像下面这样

"responseStr":"{"version":"1243423as2","location":"Americas"}"

下面是我的响应对象和映射类。

public class MyReponse implements Serializable {
private int statusCode;
private String responseStr;
//getters and setters
}

我的请求映射如下

@RestController
@Produces(MediaType.APPLICATION_JSON)
@RefreshScope
public class MyService {

 @RequestMapping(path = "/get", method = RequestMethod.GET)
 public MyReponse getReponse(
         @RequestParam MultiValueMap<String, String> requestParameterMap
) {
        //mylogic

         return (MyReponse) this.buildResponse(Status.OK, myResponse).getEntity();
}
public static final Response buildResponse(Status status, Object entity) {
    return Response.status(status).entity(entity).build();
}

【问题讨论】:

  • 不清楚你为什么要创建一个Response 对象,然后在构造它时立即取出你传入的实体。

标签: java json spring spring-boot jackson


【解决方案1】:

Spring HTTP Support

不需要创建响应。您制作 json 或集中您的逻辑。

这是示例代码:

样品控制器。

@RestController
public class SampleController {

   @RequestMapping(path = "/get", method = RequestMethod.GET)
   @ResponseBody
   public String makeJson(@RequestParam MultiValueMap<String, String> map) {

         // something...

         ObjectMapper mapper = new ObjectMapper();

         return mapper.writeValueAsString(map);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2023-03-09
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多