spring:escapeBody results in invalid JSON

前端 未结 2 658
长情又很酷
长情又很酷 2021-01-21 19:36

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 s

相关标签:
2条回答
  • 2021-01-21 19:51

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

    Here is the JSTL fn documentation

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

    0 讨论(0)
  • 2021-01-21 20:01

    The Javascript Object Notation specification states that

    Any character may be escaped.

    As such,

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

    is valid JSON.

    If you need to create really custom text, you'll need to generate it yourself in a controller handler method or other component.

    Ideally, you would use a @ResponseBody annotated method with a POJO that represents your status/body JSON object.

    0 讨论(0)
提交回复
热议问题