告诉JAXB使用注释将解组为Date类

将JAXB与Java-First一起使用时, java.util.Date类型的字段/属性将被编组并解组为xs:dateTime并且所有内容都按预期工作。

但是如果字段/属性的类型是Object ,则JAXB将xs:dateTime解组为XMLGregorianCalendarImpl

我需要找到一种方法,使用注释使JAXB将java.util.Date的日期时间值解组为java.util.Date 。 否则,我需要在每个用例中查看所有未编组的值。

即使在包含Object字段的类上定义了一些after-unmarshall-hook并手动转换实例也会很好。 但我找不到任何可以这种方式使用的东西。

请注意,我对JAXB上下文的访问权限有限,因为它在Apache CXF中使用。

您可以在@XmlElement上设置type属性。

 @XmlElement(type=Date.class) public Object getGenericDateProperty() { return date; } 

编辑:

由于您不知道可以使用XmlAdapter的类型。 如果unmarshalled值是XMLGregorianCalendar,则将其转换为Date。 有关XmlAdapter的更多信息,请参阅:

除了Blaise Doughan的回答:

我终于弄清楚了,感谢Blaise Doughan的帮助。 实际上,他的答案仅适用于一个小小的变化:如果有几种类型需要作为Object属性进行解组,则需要使用@XmlElements批注在其上放置多个@XmlElements注释。

这是我现在的代码:

 @XmlElements ({ @XmlElement(name = "dateValue", type = Date.class), @XmlElement(name = "stringValue", type = String.class), @XmlElement(name = "booleanValue", type = Boolean.class), @XmlElement(name = "listValue", type = ArrayList.class), @XmlElement(name = "bytesValue", type = Byte[].class) }) public Object getFieldValue() { return fieldValue; } 

注意:为此,需要指定“name”,因为marshaller / unmarshaller应该有一种方法来识别内容的类型。

这里有两个小问题:

  1. 您需要指定所有预期类型的​​列表(考虑到编组的情况,这是合乎逻辑的)

  2. 无法为此属性指定单个名称。 在我的情况下,在CXF Web服务中使用JAXB的地方,从.NET中的WSDL生成的代码将此字段命名为“Item”。 例如,如果有一种方法将XML元素包装在另一个具有单个名称的元素中,则生成的代码可能会更好一些。