문제

성배에서는 JSON 변환기를 사용하여 컨트롤러에서이를 수행 할 수 있습니다.

render Book.list() as JSON

렌더 결과는입니다

[
{"id":1,
 "class":"Book",
 "author":"Stephen King",
 "releaseDate":'2007-04-06T00:00:00',
 "title":"The Shining"}
]

config.groovy에서 설정을 통해 출력 날짜를 제어 할 수 있습니다.

grails.converters.json.date = 'javascript' // default or Javascript

결과는 기본 JavaScript 날짜가됩니다

[
{"id":1,
 "class":"Book",
 "author":"Stephen King",
 "releaseDate":new Date(1194127343161),
 "title":"The Shining"}
]

다음과 같은 특정 날짜 형식을 얻으려면 다음과 같습니다.

"releaseDate":"06-04-2007"

많은 타이핑이 필요한 '수집'을 사용해야합니다.

return Book.list().collect(){
  [
      id:it.id,
      class:it.class,
      author:it.author,
      releaseDate:new java.text.SimpleDateFormat("dd-MM-yyyy").format(it.releaseDate),
      title:it.title
  ]
} as JSON

이것을하는 더 간단한 방법이 있습니까?

도움이 되었습니까?

해결책

간단한 해결책이 있습니다. 성배 1.1이므로 변환기가 더 모듈 식으로 다시 작성되었습니다. 불행히도 나는 그것에 대한 문서를 완성하지 못했습니다. 이제 소위 ObjectMarShallers를 등록 할 수 있습니다. org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller 상호 작용).

원하는 출력을 달성하려면 Bootstrap.groovy에 그러한 ObjectMarShaller를 등록 할 수 있습니다.

import grails.converters.JSON;

class BootStrap {

     def init = { servletContext ->
         JSON.registerObjectMarshaller(Date) {
            return it?.format("dd-MM-yyyy")
         }
     }
     def destroy = {
     }
}

컨버터의 출력을 사용자 정의하는 몇 가지 다른 방법이 있으며 최선을 다하겠습니다. 최대한 빨리 문서를 따라 잡을 것입니다.

다른 팁

또는 날짜 수준 자체에서 일할 수 있습니다. 이것은 정확히 원하는 것이 아니지만 전체 앱에서 일관되게 작동하는 솔루션에 대한 아이디어를 불러 일으킬 수 있습니다.

def doWithDynamicMethods = {ctx ->

  def customDateToString = {->
        def dateFormat = "dd MMM yyyy"
        def timeFormat = "hh:mm:ss a"

        def timeCheck = new java.text.SimpleDateFormat("hh:mm:ss SSS a")
        def formattedTime = timeCheck.format(delegate)
        def formatString = dateFormat
        if (formattedTime != "12:00:00 000 AM") 
                              formatString = "$formatString $timeFormat"
        def formatter = new java.text.SimpleDateFormat("$formatString")
        formatter.format(delegate)
    }

    Date.metaClass.toString = customDateToString;
    java.sql.Timestamp.metaClass.toString = customDateToString;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top