Grails Date unmarshalling

前端 未结 2 528
星月不相逢
星月不相逢 2020-12-01 08:48

If I get the following json from a RESTful client, how do I elegantly unmarshal the java.util.Date? (Is it possible without providing (aka. hard-coding) the format, that\'s

2条回答
  •  Happy的楠姐
    2020-12-01 09:02

    Be aware that the new version of Grails 2.3+ supports this type of feature out of the box. See Date Formats for Data Binding

    With that said, if you are forced to use a version of Grails prior to 2.3, the CustomEditorRegistrar can be updated using the following code to eliminate the deprecation warning, and also uses the @Component annotation, which allows you to remove / skip the step of adding the bean directly in resources.groovy. Also not that I changed the grails configuration property name to grails.databinding.dateFormats, which matches the property now supported in Grails 2.3+. Finally, my version is a .groovy, not .java file.

    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))
        }
    }
    

提交回复
热议问题