我有一组属性,单个属性的每个值要么是标量(字符串,整数,...),要么是标量的集合(集合,集合,...)。下面是一个 XML 文档作为示例:
<properties xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:java="http://java.oracle.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<property name="test#1" xsi:type="xs:int">1</property>
<property name="test#2" xsi:type="java:int[]">
<value xsi:type="xs:int">1</value>
<value xsi:type="xs:int">2</value>
<value xsi:type="xs:int">3</value>
<value xsi:type="xs:int">4</value>
</property>
</properties>
这是我想使用的类,但我不知道如何正确标记值字段以使用和生成此结构。它必须以标量或标量列表的形式包含属性元素的解析内容。数据类型作为属性值存在。
@XmlRootElement(name = "property")
public class Property {
@XmlAttribute(name = "name")
protected String name;
@???
protected Object value;
}
使用两个字段protected Object scalar
和protected List<Object> list
,一个用 标记@XmlValue
,另一个用@XmlElement(name = "value")
不工作。
有人有想法吗?
更新 1
我标记Property
如下:
@XmlRootElement(name = "property")
public class Property {
@XmlAttribute(name = "name")
protected String name;
@XmlJavaTypeAdapter(Test2Adapter.class)
@XmlPath(".")
protected Object value;
}
我已经部分实现了以下适配器类
public class Test2Adapter extends XmlAdapter<AdaptedValue, Object> {
@Override
public Object unmarshal(AdaptedValue v) throws Exception {
if (v instanceof Scalar) {
return ((Scalar) v).value;
}
if (v instanceof Complex) {
return ((Complex) v).value;
}
return null;
}
@Override
public AdaptedValue marshal(Object v) throws Exception {
if (v instanceof String) {
Scalar s = new Scalar();
s.value = v;
return s;
}
if (v instanceof Collection) {
Complex c = new Complex();
c.value = (Collection<? extends Object>) v;
return c;
}
return null;
}
适应值:
@XmlSeeAlso({ Scalar.class, Complex.class })
public abstract class AdaptedValue {
}
标量:
public class Scalar extends AdaptedValue {
@XmlValue
public Object value;
}
复杂的 :
public class Complex extends AdaptedValue {
@XmlAttribute(name = "xsi:type")
public String type;
@XmlElement(name = "value")
public Collection<? extends Object> value
}
一切都正确编组,但解组不起作用。我得到以下异常:
javax.xml.bind.UnmarshalException
- with linked exception:
[Exception [EclipseLink-43] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345):
org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Missing class for indicator field value [xs:string] of type[class java.lang.String].
Descriptor:
XMLDescriptor(com.materna.osgi.service.cm.rest.resource.representation.Test2Adapter$AdaptedValue --> [])]
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:190)