在 spring rest 控制器中将 JSON 添加到模型时如何删除转义字符
How to remove escape characters when JSON is added to model in spring rest controller
我正在获取存储在数据库中的 JSON(JSON 作为字符串存储在数据库中)并将其添加到控制器中的模型对象。
@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);
}
但是当我从浏览器调用服务时,转义字符被添加到响应中。
http://localhost:8080/MyApplication/all.json
{"result":"{\"Response\":[{\"Id\":\"1\",\"Name\":\"GAD\"},{\"Id\":\"2\",\"Name\":\"GBD\"}],\"Status\":\"Success\"}"}
你能帮我把 JSON 对象发送到 web 服务中的客户端,不带转义字符吗?
您可以使用 replaceAll:
String json = serviceDao.getResponseJson();
if (json != null && !json.isEmpty()) {
model.addAttribute("result", json.replaceAll("\\", ""));
}
一定会成功的。
String str = "result':'\'\'Respon'";
String result = str.replaceAll("\\'", "");
Log.e("Result",result);
如果您使用 spring,您可以使用 @ResponseBody
并直接 return 您的 class 对象而不是字符串。
你可以参考这个link中给出的例子。
另外不要忘记包含 maven 依赖项。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
而不是直接将字符串添加到模型 return JSON
@RequestMapping(value="/all")
public @ResponseBody String getJson(){
//Logic
return json;
}
我正在获取存储在数据库中的 JSON(JSON 作为字符串存储在数据库中)并将其添加到控制器中的模型对象。
@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);
}
但是当我从浏览器调用服务时,转义字符被添加到响应中。
http://localhost:8080/MyApplication/all.json
{"result":"{\"Response\":[{\"Id\":\"1\",\"Name\":\"GAD\"},{\"Id\":\"2\",\"Name\":\"GBD\"}],\"Status\":\"Success\"}"}
你能帮我把 JSON 对象发送到 web 服务中的客户端,不带转义字符吗?
您可以使用 replaceAll:
String json = serviceDao.getResponseJson();
if (json != null && !json.isEmpty()) {
model.addAttribute("result", json.replaceAll("\\", ""));
}
一定会成功的。
String str = "result':'\'\'Respon'";
String result = str.replaceAll("\\'", "");
Log.e("Result",result);
如果您使用 spring,您可以使用 @ResponseBody
并直接 return 您的 class 对象而不是字符串。
你可以参考这个link中给出的例子。
另外不要忘记包含 maven 依赖项。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
而不是直接将字符串添加到模型 return JSON
@RequestMapping(value="/all")
public @ResponseBody String getJson(){
//Logic
return json;
}