我正在尝试编写一个应用程序,以便它能够读取这种XML并基于该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类的成员别名为“ real”,并且给出了异常。

我现在所拥有的是;

@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必填类型:projectmerger1.Point
  转换器类型:
  com.thoughtworks.xstream.converters.reflection.ReflectionConverter
  路径:/projectmerger1.Actor/attributes/point/real [2]
  行号:6类[1]:
  projectmerger1.Attributes类[2]:projectmerger1.Actor
  
  版本:1.4.6


这是一个整体错误的设置,还是可以通过一些调整继续使用它?

最佳答案

我通过更改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"));


我将继续尝试。感谢您的支持。

09-12 18:51