参考http://jackyrong.iteye.com/blog/1826699
JAXB转换JAVA OBJECT到XML的时候,对java.util.Date的转换有些要注意的地方
输出的格式为:2014-05-18T12:00:09+08:00
希望能够自定义date的format,具体解决方法如下:
要继承XmlAdapter,重写其中的方法去对日期进行格式化
编写一个class如下:
1 public class JaxbDateSerializer extends XmlAdapter<String, Date>{ 2 @Override 3 public Date unmarshal(String v) throws UFEException, ParseException { 4 SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 5 // 避免线程不安全,这里使用局部变量,而非全局变量 6 return dateformat.parse(v); 7 } 8 9 @Override 10 public String marshal(Date v) throws UFEException { 11 SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 12 return dateformat.format(v); 13 } 14 }
而后在配置文件中,对jaxbMarshaller进行如下配置:(注意adapters的list里,有上述写的类)
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="ClassesToBeBound"> <list> <value>cn.ac.iscas.pebble.ufe.bean.SearchRecord</value> <value>cn.ac.iscas.pebble.ufe.bean.Result</value> </list> </property> <property name="adapters"> <list> <bean class="cn.ac.iscas.pebble.ufe.ds.JaxbDateSerializer" /> </list> </property> </bean>
而后对于要转换成xml的bean里的date属性添加@XmlJavaTypeAdapter(JaxbDateSerializer.class)属性
比如上述的classestobebound里有两个bean,一个searchRecord,如下:
@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="parameters") public class SearchRecord { @XmlElement private Integer rid; @XmlElement private Integer fid; @XmlJavaTypeAdapter(JaxbDateSerializer.class) @XmlElement private Date time; @XmlElement private Integer sid; @XmlElement private Integer calculatestate; @XmlJavaTypeAdapter(JaxbDateSerializer.class) @XmlElement private Date lasttime; @XmlElement private Integer session; @XmlElement
……………