参见英文答案 >
jaxb unmarshal timestamp 4个
我有一个像这样的简单的xml字符串
我有一个像这样的简单的xml字符串
<table> <test_id>t59</test_id> <dateprix>2013-06-06 21:51:42.252</dateprix> <nomtest>NOMTEST</nomtest> <prixtest>12.70</prixtest> <webposted>N</webposted> <posteddate>2013-06-06 21:51:42.252</posteddate> </table>
我有像这样的xml字符串的pojo类
@XmlRootElement(name="test") public class Test { @XmlElement public String test_id; @XmlElement public Date dateprix; @XmlElement public String nomtest; @XmlElement public double prixtest; @XmlElement public char webposted; @XmlElement public Date posteddate; }
我使用jaxb for xml绑定到java对象.代码是
try { Test t = new Test JAXBContext jaxbContext = JAXBContext.newInstance(t.getClass()); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); t = (Test) jaxbUnmarshaller.unmarshal(new InputSource(new StringReader(xml))); // xml variable contain the xml string define above } catch (JAXBException e) { e.printstacktrace(); }
现在我的问题是,在与java对象绑定后,我为日期变量(dateprix和posteddata)获取了null,那么我怎么能得到这个值.
如果我使用“2013-06-06”我得到了数据对象但是对于“2013-06-06 21:51:42.252”我得到了null.
解决方法
JAXB期望XML中的日期为xsd:date(yyyy-MM-dd)或xsd:dateTime格式(yyyy-MM-ddTHH:mm:ss.sss). 2013-06-06 21:51:42.252不是有效的dateTime格式’T'(日期/时间分隔符)缺失.您需要一个自定义XmlAdapter才能使JAXB将其转换为Java Date.例如
class DateAdapter extends XmlAdapter<String,Date> { DateFormat f = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS"); @Override public Date unmarshal(String v) throws Exception { return f.parse(v); } @Override public String marshal(Date v) throws Exception { return f.format(v); } } class Type { @XmlJavaTypeAdapter(DateAdapter.class) public Date dateprix; ...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。