2009-06-08 5 views
13

RESTful 클라이언트에서 다음 json을 얻으면 java.util.Date를 우아하게 비 정렬화할 수 있습니까? (이것은 (일명 제공하지 않고있다. 하드 코딩) 형식, 즉 내가 우아하게 무슨 뜻이야 ...)Grails 날짜 언 마샬링

{ 
    "class": "url", 
    "link": "http://www.empa.ch", 
    "rating": 5, 
    "lastcrawl" : "2009-06-04 16:53:26.706 CEST", 
    "checksum" : "837261836712xxxkfjhds", 
} 

답변

18

가장 깨끗한 방법은 가능한 날짜 형식에 대한 사용자 정의 DataBinder를 등록 아마.

beans = { 
    "customEditorRegistrar"(CustomEditorRegistrar) 
} 
:

import java.beans.PropertyEditorSupport; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 

public class CustomDateBinder extends PropertyEditorSupport { 

    private final List<String> formats; 

    public CustomDateBinder(List formats) { 
     List<String> formatList = new ArrayList<String>(formats.size()); 
     for (Object format : formats) { 
      formatList.add(format.toString()); // Force String values (eg. for GStrings) 
     } 
     this.formats = Collections.unmodifiableList(formatList); 
    } 

    @Override 
    public void setAsText(String s) throws IllegalArgumentException { 
     if (s != null) 
      for (String format : formats) { 
       // Need to create the SimpleDateFormat every time, since it's not thead-safe 
       SimpleDateFormat df = new SimpleDateFormat(format); 
       try { 
        setValue(df.parse(s)); 
        return; 
       } catch (ParseException e) { 
        // Ignore 
       } 
      } 
    } 
} 

는 또한 PropertyEditorRegistrar

import org.springframework.beans.PropertyEditorRegistrar; 
import org.springframework.beans.PropertyEditorRegistry; 

import grails.util.GrailsConfig; 
import java.util.Date; 
import java.util.List; 

public class CustomEditorRegistrar implements PropertyEditorRegistrar { 
    public void registerCustomEditors(PropertyEditorRegistry reg) { 
     reg.registerCustomEditor(Date.class, new CustomDateBinder(GrailsConfig.get("grails.date.formats", List.class))); 
    } 
}   

을 구현하고 관례에 따라 grails-app/conf/봄/resources.groovy에서 스프링 빈 정의를 작성해야하는 것

그리고 마지막으로 grails-app/conf/Config.groovy에 날짜 형식을 정의하십시오 :

grails.date.formats = ["yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss"] 
+0

그루비가 아닌 자바로 구현할 이유가 있다면 궁금하십니까? 코드는 Groovy로 꽤 짧을 것입니다. –

+0

그루비가 지금보다 훨씬 느린 자바에서 비슷한 코드를 구현했습니다. Groovy는이 문제에서 큰 도약을했습니다. 나는 단지 오래된 자바 코드를 게으르지 않게 재사용하고있다 ;-) –

+0

멋진 코드 조각, 당신이하는 일의 고전. 가장 깨끗한 방법은 구문 분석을 통해 반복하지 않고 Locale을 사용하여 형식을 검색하는 것입니다. – Gepsens

5

새로운 버전의 Grails 2.3+는이 기능을 지원합니다. 이 2.3 이전 Grails의 버전을 사용하도록 강요하는 경우 CustomEditorRegistrar 가 중단 경고를 제거하려면 다음 코드를 사용하여 업데이트 할 수 있습니다, 말했다와 Date Formats for Data Binding

를 참조하고, 또한 수있는 @Component 주석을 사용 resources.groovy에 빈을 직접 추가하는 단계를 생략하거나 건너 뛸 수 있습니다. 또한 grails 설정 속성 이름을 Grails 2.3+에서 지원되는 속성과 일치하는 grails.databinding.dateFormats로 변경했습니다. 마지막으로, 제 버전은 .gava 파일이 아니라 .groovy입니다.

import javax.annotation.Resource 
import org.codehaus.groovy.grails.commons.GrailsApplication 
import org.springframework.beans.PropertyEditorRegistrar 
import org.springframework.beans.PropertyEditorRegistry 
import org.springframework.stereotype.Component 

@Component 
public class CustomEditorRegistrar implements PropertyEditorRegistrar { 

    @Resource 
    GrailsApplication grailsApplication 

    public void registerCustomEditors(PropertyEditorRegistry reg){ 
     def dateFormats = grailsApplication.config.grails.databinding.dateFormats as List 
     reg.registerCustomEditor(Date.class, new CustomDateBinder(dateFormats)) 
    } 
} 
+0

고마워요. 너는 내 하루를 구했다. @BindingFormat이 올바른 선택입니다. –

관련 문제