我正在尝试编写一个应用程序,以便能够读取此类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);
它给出了一个例外:
线程“main”中的异常com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter $ DuplicateFieldException: 重复字段y ----调试信息----字段:y类:projectmerger1.Point required-type:projectmerger1.Point 转换器类型: com.thoughtworks.xstream.converters.reflection.ReflectionConverter 路径:/projectmerger1.Actor/attributes/point/real[2] 行号:6类[1]: projectmerger1.Attributes class [2]:projectmerger1.Actor
版本:1.4.6
这是一个错误的设置整体还是我可以通过一些调整继续使用它?
答案 0 :(得分:0)
我通过改变Point类来解决它;
public class Point {
/*
@XStreamAlias("real")
@XStreamAlias("real2")
public Real y = new Real("y", "21");
@XStreamAsAttribute
public String id = "position";
*/
@XStreamImplicit
public List xy = new ArrayList();
public void add(Real entry) {
xy.add(entry);
}
}
并将其添加到我的Test.java:
actor2.attributes.point.add(new Real("x","0"));
actor2.attributes.point.add(new Real("y","0"));
我会继续尝试这个。感谢您的支持。