Spring MVC 返回的 JSON 带有斜杠 转义

来源:互联网 发布:sql unique key 编辑:程序博客网 时间:2024/06/05 12:45

我的框架是会在返回类型上加一个包装结果,但是我留了一个缺口,就是返回String 不会包装。最近写了一个接口,因为是以前的接口返回,不能改返回结果,所以我返回String 不会被包装,代码如下:

    @RequestMapping(value = "webSwitch")    public Object webSwitch() {        JsonObject result = new JsonObject();        result.addProperty("success", 200);        result.addProperty("message", "ok");        result.addProperty("openWeb", showWebVO.getOpenWeb());        return result.toString();    }

测试结果返回的结果 带有反斜杠,不能被json 解析。结果如下:

"{\"success\":200,\"message\":\"ok\",\"openWeb\":true,\"webUrl\":null}"

原因分析:因为 我的框架里面把 CustomGsonMessageConvertor 放在第一位,所以默认用它来write response。结果 gson 写字符串时候 发现有 json格式的特殊字符就会加转义。

搞清楚原因之后,添加 produces = “text/plain” 被 StringhttpMessageConvertor 写回就没事了。