【问题标题】:XML Date Binding to Java Object Date [duplicate]XML日期绑定到Java对象日期[重复]
【发布时间】:2013-06-11 16:35:42
【问题描述】:

我有一个像这样的简单 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 将 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)为空,所以我怎么能得到这个值。

如果我使用“2013-06-06”,我得到了数据对象,但对于“2013-06-06 21:51:42.252”,我得到了 null。

【问题讨论】:

标签: java xml jaxb


【解决方案1】:

JAXB 需要 xsd:date (yyyy-MM-dd) 或 xsd:dateTime 格式 (yyyy-MM-ddTHH:mm:ss.sss) 中的 XML 日期。 2013-06-06 21:51:42.252 不是有效的 dateTime 格式“T”(日期/时间分隔符)丢失。您需要一个自定义 XmlAdapter 以使 JAXB 将其转换为 Java 日期。例如

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;
...

【讨论】:

  • 这对 java.util.date 没问题,但是 java.sql.date 呢??
  • 如果是 2013-06-06 21:51:42.256 那么应该是 Timestamp 然后使用 Timestamp.valueOf(str);解析和 toString() 格式化
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 2019-06-05
相关资源
最近更新 更多