spring:escapeBody导致无效的JSON

时间:2014-08-25 17:39:11

标签: java json spring jsp

我试图在JSP中转义字符串以在AJAX调用上返回有效的JSON,但spring:escapeBody标记未正确转义JSON的单引号。有效的JSON不应该转义单引号。

<%@ page trimDirectiveWhitespaces="true" contentType="json/application"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
{
"status": "success",
"body" : "<spring:escapeBody javaScriptEscape="true"> 
           if you don't have "user" an account
           </spring:escapeBody>"
 }

所以这段代码评估为:

{
"status": "success",
"body" : "if you don\'t have \"user\" an account"
 }

但有效的JSON需要它:

{
"status": "success",
"body" : "if you don't have \"user\" an account"
 }

无论如何我无法使用escapeBody标签逃脱单引号? 或者我可以使用另一个标签吗?也许是JSTL功能?

2 个答案:

答案 0 :(得分:2)

Javascript Object Notation specification表示

  

任何角色都可能被转义。

因此,

{
    "status": "success",
    "body" : "if you don\'t have \"user\" an account"
}

是有效的JSON。

如果您需要创建真正的自定义文本,则需要在控制器处理程序方法或其他组件中自行生成它。

理想情况下,您可以使用带有POJO的@ResponseBody带注释的方法来表示您的状态/正文JSON对象。

答案 1 :(得分:2)

正如Ryan在Sotirios Delimanolis的回答(非常好)中所指出的那样:

所以它似乎只是一个实施选择,现在让我们留下一个并非真正一贯实施的标准......叹息

无论如何,这是一个可以用来使代码正常工作的解决方法

<%@ page trimDirectiveWhitespaces="true" contentType="json/application"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%-- 
    [1] Removing the escape of the single quote character: jQuery's Ajax cannot handle it
            stackoverflow.com/questions/25491391/springescapebody-results-in-invalid-json
            stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response
--%>
<c:set var="someJsonData" >
    <spring:escapeBody javaScriptEscape="true"> 
               if you don't have "user" an account
    </spring:escapeBody>
</c:set>    
{
    "status": "success",
    "body" : "${fn:replace(someJsonData, "\\\'","'")}" , <%-- [1] --%>
}

Here is the JSTL fn documentation

说实话,可能不是最干净/最好的解决方案。但是直到你找到更好的方法才能胜任。