我正在使用 XStream。目前,用其他东西替换 XStream 并不容易。
我有一个接口(MyInterface)和几个实现该接口的子类(在下面的示例代码中,有一个称为 MyImplementation)。
我想序列化和反序列化子类的实例。我发现如果我将类属性放入 XML 中,我可以很好地反序列化:
<myInterfaceElement class="myPackage.MyImplementation">
<field1>value1</field1>
<field2>value2</field2>
</myInterfaceElement>
但是,我不知道如何让 XStream 写入类属性。序列化时如何让 XStream 包含类属性?或者是否有另一种方法来序列化/反序列化类层次结构,以便所有实现的元素名称相同,并且每个子类都可以定义自己的字段?
这是一个 MyInterface、MyImplementation 的示例,这是一个试图使其工作的 JUnit 测试用例。deserializeWithClassAttribute 测试通过,而 classAttributeSetInResult 失败。
package myPackage;
public interface MyInterface {
}
package myPackage;
public class MyImplementation implements MyInterface {
public String field1;
public String field2;
public MyImplementation(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
}
package myPackage;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import static org.junit.Assert.*;
public class xstreamTest {
@Test
public void classAttributeSetInResult() {
MyInterface objectToSerialize = new MyImplementation("value1", "value2");
final XStream xStream = new XStream(new DomDriver());
xStream.alias("myInterfaceElement", MyInterface.class);
String xmlResult = xStream.toXML(objectToSerialize).toString();
String expectedResult =
"<myInterfaceElement class=\"myPackage.MyImplementation\">\n" +
" <field1>value1</field1>\n" +
" <field2>value2</field2>\n" +
"</myInterfaceElement>";
assertEquals(expectedResult, xmlResult);
}
@Test
public void deserializeWithClassAttribute() {
String inputXmlString =
"<myInterfaceElement class=\"myPackage.MyImplementation\">\r\n" +
" <field1>value1</field1>\r\n" +
" <field2>value2</field2>\r\n" +
"</myInterfaceElement>";
final XStream xStream = new XStream(new DomDriver());
MyInterface result = (MyInterface)xStream.fromXML(inputXmlString);
assertTrue("Instance of MyImplementation returned", result instanceof MyImplementation);
MyImplementation resultAsMyImplementation = (MyImplementation)result;
assertEquals("Field 1 deserialized", "value1", resultAsMyImplementation.field1);
assertEquals("Field 2 deserialized", "value2", resultAsMyImplementation.field2);
}
}