简体   繁体   English

Spring Rest API控制器的意外JSon响应

[英]Unexpected JSon response from Spring Rest API Controller

I have a method in my Spring controller, in which I am returning an object containing a spring attribute with a value "\\HelloWorld" . 我的Spring控制器中有一个方法,其中我返回一个对象,该对象包含一个带有spring属性的值“ \\ HelloWorld” To store it into Java String object I have to put escape character, then the string becomes "\\\\HelloWorld" . 要将其存储到Java String对象中,我必须放置转义字符,然后字符串变为“ \\\\ HelloWorld” When I print, that works totally fine and prints "\\HelloWorld" . 当我打印时,这完全可以正常工作并打印“ \\ HelloWorld” but when I return it in JSon response, it's returning "\\\\HelloWorld" . 但是当我在JSon响应中返回它时,它正在返回“ \\\\ HelloWorld”

But I want it to return "\\HelloWorld" . 但是我希望它返回“ \\ HelloWorld”

Bellow is the snippet: 波纹管是片段:

   @RequestMapping("") 
    @ResponseBody
    public MyDataObject greeting() {
       MyDataObject f = new MyDataObject();
        f.setMessage("\\HelloWorld");
        return f;
    }

It's Json response is "message":"\\\\HelloWorld", but I want it "\\HelloWorld". 它的Json响应是“ message”:“ \\\\ HelloWorld”,但我希望它是“ \\ HelloWorld”。

Note: I don't want to unescape manually specific to that string. 注意:我不想手动取消特定于该字符串的转义。

You can use a library such as Jakson and it will internally handle such complexities. 您可以使用Jakson之类的库,它将在内部处理此类复杂性。

MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
String payload = new ObjectMapper().writeValueAsString(params);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM