简体   繁体   中英

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" . To store it into Java String object I have to put escape character, then the string becomes "\\\\HelloWorld" . When I print, that works totally fine and prints "\\HelloWorld" . but when I return it in JSon response, it's returning "\\\\HelloWorld" .

But I want it to return "\\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".

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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