如果我从RESTful客户端获得以下json,如何优雅地解组java.util.Date?(是否可以不提供(又称为硬编码)格式,这就是我的优雅意思。)
{ "class": "url", "link": "http://www.empa.ch", "rating": 5, "lastcrawl" : "2009-06-04 16:53:26.706 CEST", "checksum" : "837261836712xxxkfjhds", }
最干净的方法可能是为可能的日期格式注册自定义DataBinder。
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 / spring / resources.groovy中创建一个Spring-bean定义:
beans = { "customEditorRegistrar"(CustomEditorRegistrar) }
最后在您的grails-app / conf / Config.groovy中定义日期格式:
grails.date.formats = ["yyyy-MM-dd HH:mm:ss.SSS ZZZZ", "dd.MM.yyyy HH:mm:ss"]