gpt4 book ai didi

java - spring:escapeBody 导致无效的 JSON

转载 作者:行者123 更新时间:2023-11-29 03:17:49 25 4
gpt4 key购买 nike

我试图转义 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 函数?

最佳答案

正如 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

老实说,这可能不是最干净/最好的解决方案。但它会起到作用,直到您找到更好的为止。

关于java - spring:escapeBody 导致无效的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com