복붙노트

[SPRING] spring : escapeBody 결과 JSON이 잘못되었습니다.

SPRING

spring : escapeBody 결과 JSON이 잘못되었습니다.

AJAX 호출에서 유효한 JSON을 반환하도록 JSP에서 문자열을 이스케이프하려고 시도하지만 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 기능일까요?

해결법

  1. ==============================

    1.Ryan이 Sotirios Delimanolis의 답변에 대한 (아주 좋은) 의견으로 지적한 바와 같이 :

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

    다음은 JSTL fn documentation입니다.

    아마도 솔직히 말해서 가장 깨끗한 / 최선의 해결책은 아닙니다. 그러나 당신이 더 나은 것을 발견 할 때까지 그것은 일을합니다.

  2. ==============================

    2.Javascript Object Notation 사양은

    Javascript Object Notation 사양은

    이와 같이,

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

    유효한 JSON입니다.

    정말로 사용자 정의 텍스트를 작성해야하는 경우, 컨트롤러 핸들러 메소드 또는 다른 컴포넌트에서 직접 사용자 정의 텍스트를 생성해야합니다.

    이상적으로는 @ResponseBody 주석 메소드를 상태 / 본문 JSON 객체를 나타내는 POJO와 함께 사용하는 것이 좋습니다.

  3. from https://stackoverflow.com/questions/25491391/springescapebody-results-in-invalid-json by cc-by-sa and MIT license