2012-09-15 4 views
2

REST 호출을하는 grails 앱이 있습니다. 오류가 발생하면 오류 메시지가 포함 된 JSON 배열이 반환됩니다. 이 문자열을 단일 문자열로 결합해야합니다. 그러나 그렇게 할 때 큰 따옴표가 문자열 앞과 끝에 추가됩니다.JSONArray에 가입하면 Groovy 문자열에 큰 따옴표가 추가됩니다.

import net.sf.json.* 
class MyController { 

    def test = { 

     String msg = "'fred' is not a valid LDAP distinguished name." 
     JSONArray messages = new JSONArray() 
     messages.add(msg) 
     def renderStr = messages.join('<br/>') 

     render(renderStr) 
    } 
} 

출력은 다음과 같다 : I 문제를 설명하기위한 간단한 테스트 컨트롤러를 작성한

"'fred' is not a valid LDAP distinguished name." 

답변

3

문제 있습니다 ... JSON 스펙 스트링을 리턴하는, 따른 기능에 참여한다는 것이다 여기에 자신의 문서에 : http://grails.org/doc/1.0.3/api/org/codehaus/groovy/grails/web/json/JSONArray.html

The texts produced by the toString methods strictly conform to JSON syntax rules. The constructors are more forgiving in the texts they will accept: 

    An extra , (comma) may appear just before the closing bracket. 
    The null value will be inserted when there is , (comma) elision. 
    Strings may be quoted with ' (single quote). 
    Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ]/\ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null. 
    Values can be separated by ; (semicolon) as well as by , (comma). 
    Numbers may have the 0- (octal) or 0x- (hex) prefix. 
    Comments written in the slashshlash, slashstar, and hash conventions will be ignored. 

참고가 ㄱ하지 않으면 규칙은 문자열의 모든 에서 인용 할 필요가 없다 "는 것을 따옴표 또는 작은 따옴표 "와 함께 egin이 발생했습니다. 문자열은 따옴표로 시작하므로 따옴표없이 출력 된 경우 JSON 파서는 두 번째 작은 따옴표에서 끝나는 문자열을 가정하고 이후의 텍스트는 분석 할 수없는 쓰레기가됩니다.

0

사용이 편리한 방법

private String joinJSONArray(arr, delim = ',') { 
    def result = '' 

    arr.eachWithIndex { e, i -> 
     result += e 

     if (i != arr.size() - 1) { 
      result += delim 
     } 
    } 

    result 
} 

그루비가 injectWithIndex을 제공하지 아무튼 그것은이 eachWithIndex를 사용합니다.

관련 문제