【发布时间】:2013-12-15 15:37:52
【问题描述】:
我正在尝试编写一个应用程序,以便它能够读取这种 XML 并基于它创建整个对象;
<actor id="id273211" PGFVersion="0.19" GSCVersion="0.10.4">
<attributes>
<text id="name">Actor 1b</text>
<point id="position">
<real id="x">0</real>
<real id="y">0</real>
</point>
</attributes>
</actor>
我的问题是我将 Point 类的成员别名为“真实”,它给出了一个例外。
我现在拥有的是;
@XStreamAlias("actor")
public class Actor {
@XStreamAsAttribute
String id = "",PGFVersion = "", GSCVersion = "";
Attributes attributes = new Attributes();
}
public class Attributes {
public Text text = new Text("name", "Actor 1");
public Point point = new Point();
}
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"value"})
@XStreamAlias("text")
public class Text {
@XStreamAsAttribute
String id;
String value;
public Text(String text, String value) {
this.id = text;
this.value = value;
}
public class Point {
@XStreamAlias("real")
public Real x = new Real("x", "11");
@XStreamAlias("real")
public Real y = new Real("y", "21");
@XStreamAsAttribute
public String id = "position";
}
还有我的 Test.java:
public static void main(String[] args) throws Exception {
XStream xstream = new XStream();
Actor actor2 = new Actor();
xstream.processAnnotations(Text.class);
xstream.processAnnotations(Real.class);
xstream.processAnnotations(Point.class);
xstream.processAnnotations(Actor.class);
String xml = xstream.toXML(actor2);
System.out.println(xml);
}
这样就完美输出了XML,如下:
<actor id="" PGFVersion="" GSCVersion="">
<attributes>
<text id="name">Actor 1</text>
<point id="position">
<real id="x">11</real>
<real id="y">21</real>
</point>
</attributes>
</actor>
但是当我尝试使用以下方式导入它时:
String xml = xstream.toXML(actor2);
Actor actorNew = (Actor)xstream.fromXML(xml);
System.out.println(xml);
它给出了一个例外:
线程“主”com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$DuplicateFieldException 中的异常: 重复字段 y ---- 调试信息 ---- field : y class : projectmerger1.Point required-type : projectmerger1.Point 转换器类型: com.thoughtworks.xstream.converters.reflection.ReflectionConverter 路径:/projectmerger1.Actor/attributes/point/real[2] 行号:6 类[1]: projectmerger1.Attributes 类[2] : projectmerger1.Actor
版本:1.4.6
这是一个整体错误的设置,还是我可以通过一些调整继续使用它?
【问题讨论】: