我有一个像这样定义的DateTimeTypeAdapter:
public class DateTimeAdapter extends XmlAdapter<String, DateTime>{
@Override
public DateTime unmarshal(String value) throws Exception {
return new DateTime(value);
}
@Override
public String marshal(DateTime value) throws Exception {
return value.toString();
}
}
包装注释: @XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(type = DateTime.class,value = DateTimeAdapter.class)}) package srm.model; import org.joda.time.DateTime;
我正试图将DateTime编组:
@Test
public void foo() throws Exception {
Root root = new Root();
root.dateTime = new DateTime(2011, 5, 30, 11, 2, 30, 0);
JAXBContext jc = JAXBContext.newInstance(Root.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(root, System.out);
JAXBElement<?> element = createElement("a", DateTime.class, root.dateTime);
marshaller.marshal(element, System.out);
}
private static <T> JAXBElement<T> createElement(String name, Class<T> type, Object value) {
return new JAXBElement<>(new QName(name), type, type.cast(value));
}
前两个调用成功但第三个调用抛出异常:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<dateTime>2011-05-30T11:02:30.000-07:00</dateTime>
</root>
<root>
<dateTime>2011-05-30T11:02:30.000-07:00</dateTime>
</root>
javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.internal.SAXException2: org.joda.time.DateTime is not known to this context
javax.xml.bind.JAXBException: org.joda.time.DateTime is not known to this context]
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:311)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:95)
at srm.model.XmlTest.foo(XmlTest.java:259)
如何使这项工作?谢谢!
答案 0 :(得分:0)
XmlAdapter
永远不会应用于根对象。相反,您可以转换对象,然后将转换后的对象放在JAXBElement
中,然后封送它。