加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML日期绑定到Java对象日期

发布时间:2020-12-16 23:11:44 所属栏目:百科 来源:网络整理
导读:参见英文答案 jaxb unmarshal timestamp????????????????????????????????????4个 我有一个像这样的简单的xml字符串 table test_idt59/test_id dateprix2013-06-06 21:51:42.252/dateprix nomtestNOMTEST/nomtest prixtest12.70/prixtest webpostedN/webpost
参见英文答案 > jaxb unmarshal timestamp????????????????????????????????????4个
我有一个像这样的简单的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;
...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读