3

在反序列化 Xml 时,我遇到了 java 泛型和 xstream 的问题。

这是主要的 DTO

@XStreamAlias("OBJECTX")
public class ObjectX<T> {

    @XStreamAlias("DATA")
    private T t;

    ... getter and setter ...

}

这是主 DTO 中的 Data 对象

@XStreamAlias("DATA")
public class FolderXml {

    @XStreamAlias("DIGITION_NAME")
    private String digitionName;

    @XStreamAlias("FOLDER_ID")
    private int folderId;

    ...getters and setters...

}

这是反序列化的 Xml 示例

<?xml version="1.0" encoding="UTF-8"?>
<OBJECTX>
        <DATA>
            <DIGITION_NAME>TVC_ACT2</DIGITION_NAME>
            <FOLDER_ID>1234</FOLDER_ID>
        </DATA>
</OBJECTX>

这是实际的代码

StaxDriver staxDriver = new StaxDriver(new NoNameCoder());
XStream xstream = new XStream(staxDriver);
xstream.processAnnotations(ObjectX.class);
xstream.alias("DATA", FolderXml.class);
ObjectX<FolderXml> obj=  (ObjectX<FolderXml>) xstream.fromXML(xml);

例外是

com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field java.lang.Object.DIGITION_NAME
---- Debugging information ----
field               : DIGITION_NAME
class               : java.lang.Object
required-type       : java.lang.Object
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path                : /OBJECTX/DATA/DIGITION_NAME
line number         : 4
class[1]            : cat.ccma.digition.digitionservicecontroller.objects.base.ObjectX
version             : null
-------------------------------
4

1 回答 1

2

修改您的代码以添加泛型的默认实现。

    StaxDriver staxDriver = new StaxDriver(new NoNameCoder());
    XStream xstream = new XStream(staxDriver);
    xstream.processAnnotations(ObjectX.class);
    xstream.processAnnotations(FolderXml.class);
    xstream.alias("DATA", FolderXml.class);
    xstream.addDefaultImplementation(FolderXml.class,ObjectX.class.getDeclaredField("t").getType());
    ObjectX<FolderXml> obj=  (ObjectX<FolderXml>) xstream.fromXML(xml);
于 2017-07-17T10:40:14.810 回答