我想将对象转换为xml,它需要为String数据类型提供别名。例如:
public class ArrayTest
{
private int id=4;
public String area[];
public void setArea(String ar[])
{
area = ar;
}
}
对象到xml转换类就像:
public class Test
{
public static void main(String args[])
{
String area[] = {"ABC","XYZ","PRQ"};
ArrayTest at = new ArrayTest();
at.setArea(area);
Xstream stream = new XStream(new staxDriver());
stream.alias("response",ArrayTest.class);
System.out.println(stream.toXML(at));
}
}
我的输出为:
<?xml version="1.0" ?>
<response>
<id>4</id>
<area>
<string>ABC</string>
<string>XYZ</string>
<string>PRQ</string>
</area>
</response>
但我希望输出为:
<?xml version="1.0" ?>
<response>
<id>4</id>
<area>
<code>ABC</code>
<code>XYZ</code>
<code>PRQ</code>
</area>
</response>
我是XStream的新手,请帮助我
答案 0 :(得分:1)
您可以使用:
stream.addImplicitArray(ArrayTest.class, "area", "code");
答案 1 :(得分:1)
我认为这可行:
首先为area
public class ArrayTest {
private int id = 4;
private String[] area;
public void setArea(String ar[]) {
area = ar;
}
public String[] getArea() {
return area;
}
}
然后添加NamedArrayConverter
转换器:
public static void main(String args[]) {
String area[] = { "ABC", "XYZ", "PRQ" };
ArrayTest at = new ArrayTest();
at.setArea(area);
XStream stream = new XStream();
stream.alias("response",ArrayTest.class);
stream.registerConverter(new NamedArrayConverter(at.getArea().getClass(), null, "code"));
System.out.println(stream.toXML(at));
}
这是输出:
<response>
<id>4</id>
<area>
<code>ABC</code>
<code>XYZ</code>
<code>PRQ</code>
</area>
</response>