我正在获取存储在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);
}
但是当我从浏览器调用服务时,会在响应中添加转义字符。
http://localhost:8080/MyApplication/all.json
{ “结果”: “{\” 响应\ “:[{\” ID \ “:\” 1 \” \ “名称\”:\ “GAD \”},{\ “ID \”: \ “2 \” \ “名称\”:\ “GBD \”}],\ “状态\”:\ “成功\”}“}
在没有转义字符的网络服务中,您可以帮助我将JSON对象发送到客户端。
答案 0 :(得分:2)
而不是将字符串添加到模型直接返回JSON
@RequestMapping(value="/all")
public @ResponseBody String getJson(){
//Logic
return json;
}
答案 1 :(得分:1)
它肯定会奏效。
String str = "result':'\'\'Respon'";
String result = str.replaceAll("\\\'", "");
Log.e("Result",result);
答案 2 :(得分:0)
您可以使用replaceAll:
String json = serviceDao.getResponseJson();
if (json != null && !json.isEmpty()) {
model.addAttribute("result", json.replaceAll("\\\\", ""));
}
答案 3 :(得分:0)
如果您使用的是spring,则可以使用@ResponseBody
并直接返回您的类对象而不是String。
您可以参考此link中给出的示例。
另外不要忘记包含maven依赖。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>