2

我收到以下设置的 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
原因异常:com.thoughtworks.xstream.mapper.CannotResolveClassException
原因消息:2:2
类:[...]RequestTO
required-type :[...]SkuMerchTO
路径:/RequestTO/skuNumberList/skuMerch
行号:3
.-------------------------------------------- -
com.thoughtworks.xstream.converters.ConversionException:2:2:2:2
----调试信息----
消息:2:2
原因异常:com.thoughtworks.xstream.mapper.CannotResolveClassException
原因消息: 2:2
类:[...]RequestTO
所需类型:[..]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));  

它在 from XML 部分仍然失败!

4

1 回答 1

3

命名的属性class对 XStream 具有特殊含义,这个问题表明您可以通过类似的方式告诉 XStream 为此目的使用不同的属性

stream.aliasSystemAttribute("__class", "class");

这将导致 XStream__class用作“特殊”属性,并被class视为普通属性。或者,如果您知道您的任何对象都不需要 XStream 魔法处理,class您可以说

stream.aliasSystemAttribute(null, "class");

to tell it not to use this feature at all.

You may also need to use itemFieldName="skuMerch" on the @XStreamImplicit annotation, as per the XStream annotation tutorial.

于 2012-12-10T15:21:42.103 回答