spring:escapeBody导致无效的JSON [英] spring:escapeBody results in invalid JSON

查看:212
本文介绍了spring:escapeBody导致无效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to escape a string in a JSP to return valid JSON on an AJAX call however the spring:escapeBody tag is not correctly escaping single quotes for JSON. Valid JSON should not escape single quotes.

<%@ 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需要它:

but valid JSON needs it to be:

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

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

is there anyway I can not escape the single quote with the escapeBody tag? Or is there another tag I can use? maybe a JSTL function?

推荐答案

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

As pointed out by Ryan in the (very good) comments of Sotirios Delimanolis's answer:

  • The Javascript Object Notation specification states that Any character may be escaped. So obviously this means that even single quotes characters can be.
  • However as pointed out by Ryan (again in the same comments), this is raised as an error by jQuery's Ajax implementation. see jQuery single quote in JSON response

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

So it seems like it's simply an implementation choice that is now leaving us with a standard that's not really consistently implemented... sigh

无论如何,这是一个可以用来使你的代码工作的工作

Anyway, here is a work around you can use to get your code working

<%@ 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] --%>
}

这是 JSTL fn 文档

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

Probably not the cleanest/best solution to be honest. But it does the job until you find better.

这篇关于spring:escapeBody导致无效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆