我通过以下设置获得XStream错误。我一定很疯狂。怎么了?
请求类
@XStreamAlias("RequestTO")
public class RequestTO {
@XStreamImplicit
private List<SkuMerchTO> skuNumbers;
...
}
嵌套对象类
@XStreamAlias("skuMerch")
public class SkuMerchTO {
@XStreamAlias("skuNumber")
@XStreamAsAttribute
private Integer skuNumber;
@XStreamAlias("dept")
@XStreamAsAttribute
private Short department;
@XStreamAlias("class")
@XStreamAsAttribute
private Short cls;
@XStreamAlias("subClass")
@XStreamAsAttribute
private Short subClass;
...
}
将XML解码为对象的XStream代码:
XStream stream = new XStream();
stream.processAnnotations(SkuMerchTO.class);
stream.processAnnotations(RequestTO.class);
RequestTO request = (RequestTO)stream.fromXML(requestXml);
XML输入字符串:
<RequestTO>
<skuMerch skuNumber="123456" dept="1" class="2" subClass="3"/>
<skuMerch skuNumber="234567" dept="4" class="5" subClass="6"/>
</RequestTO>
Stacktrace中的错误:
----调试信息----
消息:2:2
cause-exception:com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message:2:2
课程:[...] RequestTO
必需类型:[...] SkuMerchTO
路径:/ RequestTO / skuNumberList / skuMerch
行号:3
.-------------------------------
com.thoughtworks.xstream.converters.ConversionException:2:2:2:2
----调试信息----
消息:2:2
cause-exception:com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message:2:2
课程:[...] RequestTO
required-type:[..] SkuMerchTO
路径:/ RequestTO / skuNumberList / skuMerch
行号:3
.-------------------------------
如果我创建对象并执行toXML,我会得到:
<RequestTO>
<skuMerch skuNumber="0" dept="1" class="2" subClass="2"/>
<skuMerch skuNumber="1" dept="1" class="2" subClass="2"/>
<skuMerch skuNumber="2" dept="1" class="2" subClass="2"/>
</RequestTO>
编辑:如果这样做,那很有趣:
stream.fromXML(stream.toXML(object));
它仍然在XML部分失败!
答案 0 :(得分:3)
名为class
的属性对XStream具有特殊含义,this question建议您可以通过
stream.aliasSystemAttribute("__class", "class");
这会导致XStream使用__class
作为“特殊”属性,并将class
视为正常属性。或者,如果您知道对于任何对象都不需要class
的XStream魔术处理,则可以说
stream.aliasSystemAttribute(null, "class");
告诉它根本不要使用此功能。
根据XStream annotation tutorial,您可能还需要在itemFieldName="skuMerch"
注释上使用@XStreamImplicit
。