使用SimpleFramework解析日期

我收到一个XML响应,其属性包含以下值:

Wed Sep 05 10:56:13 CEST 2012 

我在我的模型类中定义了一个带注释的字段:

 @Attribute(name = "regDate") private Date registerDate; 

但是它引发了一个例外:

 java.text.ParseException: Unparseable date: "Wed Sep 05 10:56:13 CEST 2012" (at offset 0) 

是否可以在SimpleFramework的注释中定义日期格式?

该日期字符串应包含哪种格式?

SimpleXML仅支持一些DateFormat

  • yyyy-MM-dd HH:mm:ss.S z
  • yyyy-MM-dd HH:mm:ss z
  • yyyy-MM-dd z
  • YYYY-MM-DD

(有关每个字符的含义,请参阅SimpleDateFormat API Doc(Java SE 7) )

但是,可以编写处理其他格式的自定义Transform

转变

 public class DateFormatTransformer implements Transform { private DateFormat dateFormat; public DateFormatTransformer(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public Date read(String value) throws Exception { return dateFormat.parse(value); } @Override public String write(Date value) throws Exception { return dateFormat.format(value); } } 

相应的注释

 @Attribute(name="regDate", required=true) /* 1 */ private Date registerDate; 

注1: required=true是可选的

如何使用它

 // Maybe you have to correct this or use another / no Locale DateFormat format = new SimpleDateFormat("EE MMM dd HH:mm:ss z YYYY", Locale.US); RegistryMatcher m = new RegistryMatcher(); m.bind(Date.class, new DateFormatTransformer(format)); Serializer ser = new Persister(m); Example e = ser.read(Example.class, xml);