简体   繁体   English

无法使用JAXBElement封送XmlJavaTypeAdapter吗?

[英]Cannot use JAXBElement to marshal XmlJavaTypeAdapter?

I have a DateTimeTypeAdapter defined like this: 我有一个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();
  }
}

And the package is annotated: @XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(type=DateTime.class, value=DateTimeAdapter.class)}) package srm.model; 并且对该程序包进行了注释:@XmlJavaTypeAdapters({@ XmlJavaTypeAdapter(type = DateTime.class,value = DateTimeAdapter.class)})程序包srm.model; import org.joda.time.DateTime; 导入org.joda.time.DateTime;

And I am trying to marshal the DateTime out: 我正在尝试将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));
}

The first two calls succeed but the third one throws an exception: 前两个调用成功,但第三个调用引发异常:

<?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)

How to make this work? 如何使这项工作? Thanks! 谢谢!

An XmlAdapter is never applied to the root object. XmlAdapter永远不会应用于根对象。 Instead you can convert the object and then put the converted object in the JAXBElement and then marshal that. 相反,您可以转换对象,然后将转换后的对象放入JAXBElement ,然后将其编组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM