java 将 JSON 添加到 Spring Rest 控制器中的模型时如何删除转义字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33117235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:12:55  来源:igfitidea点击:

How to remove escape characters when JSON is added to model in spring rest controller

javajsonspringrestspring-rest

提问by Anand Sai Krishna

I am fetching JSON stored in DB (JSON is stored as a string in DB) and adding it to the model object in the controller.

我正在获取存储在 DB 中的 JSON(JSON 作为字符串存储在 DB 中)并将其添加到控制器中的模型对象中。

@RequestMapping( method = RequestMethod.GET, value = "/all" )
public void getJson(HttpServletRequest httpServletRequest, Model model){

    String json = serviceDao.getResponseJson(); 
    System.out.println(json); //Output: {"Response":[{"Id":"1","Name":"GAD"},{"Id":"2","Name":"GBD"}],"Status":"Success"}
    model.addAttribute("result",json);
}

But when I invoke the service from a browser, escape characters are added the response.

但是当我从浏览器调用服务时,响应中添加了转义字符。

http://localhost:8080/MyApplication/all.json

{"result":"{\"Response\":[{\"Id\":\"1\",\"Name\":\"GAD\"},{\"Id\":\"2\",\"Name\":\"GBD\"}],\"Status\":\"Success\"}"}

http://localhost:8080/MyApplication/all.json

{"result":"{\"Response\":[{\"Id\":\"1\",\"Name\":\"GAD\"},{\"Id\":\"2 \",\"名称\":\"GBD\"}],\"状态\":\"成功\"}"}

Can you please help me on the way to send the JSON object to the client in a webservice without escape characters.

您能否帮助我在没有转义字符的情况下将 JSON 对象发送到 Web 服务中的客户端。

采纳答案by Angelo Angeles

Instead of adding the string to model return JSON directly

而不是将字符串添加到模型直接返回 JSON

@RequestMapping(value="/all")
public @ResponseBody String getJson(){
   //Logic
    return json; 
}

回答by Karan Nassa

It will work definitely.

它肯定会起作用。

 String str = "result':'\'\'Respon'";
 String result = str.replaceAll("\\'", ""); 
 Log.e("Result",result);

回答by Naman Gala

If you are using spring, you can use @ResponseBodyand directly return your class object instead of String.

如果您使用的是 spring,则可以使用@ResponseBody并直接返回您的类对象而不是 String。

You can refer example given in this link.

您可以参考此链接中给出的示例。

Also don't forget to include maven dependency.

也不要忘记包含 maven 依赖项。

<dependency>
    <groupId>org.codehaus.Hymanson</groupId>
    <artifactId>Hymanson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>

回答by Guilherme Arthur de Carvalho

You can use replaceAll:

您可以使用 replaceAll:

String json = serviceDao.getResponseJson();

if (json != null && !json.isEmpty()) {
    model.addAttribute("result", json.replaceAll("\\", ""));
}