XStream不会转换xml标记

时间:2014-04-22 14:54:22

标签: java xml xstream

我有一个xml。我想转换为对象,xstream转换所有标签,除了其中一个,它给出null。

对这个问题有什么看法吗?

xml

  <person>
  <name>nnn</name>
  <age>aaa</age>
  <address>
    <city>ccc</city>
    <countryco</country>
  </address>
  </person>

代码java

  XStream _xstream = new XStream();
  _xstream.setMode(XStream.NO_REFERENCES);
  _xstream.aliasType("person", PersonType.class);
  _xstream.aliasType("address", PersonType.class);
  _xstream.aliasField("city", AddressType.class, "city");
  _xstream.aliasField("country", AddressType.class, "country");

当我检查对象人员时,所有变量都可以,但地址始终为null

我试过这个:

_xstream.aliasType("person", PersonType.class);
_xstream.aliasType("address", AddressType.class);
_xstream.aliasField("city", AddressType.class, "city");
_xstream.aliasField("country", AddressType.class, "country");

但仍然没有工作!

3 个答案:

答案 0 :(得分:0)

在这种情况下,别名的使用是多余的。 XStream将自动转换字段的名称。

你的地址似乎是一种嵌套类型。您对两个别名使用相同的类型:

_xstream.aliasType("person", PersonType.class);
_xstream.aliasType("address", PersonType.class);

应该是

_xstream.aliasType("address", AddressType.class);

用于地址别名。

答案 1 :(得分:0)

Java代码:

 @XStreamAlias("person")
 public class Person {

 @XStreamAlias("name")
 private String Name;

 @XStreamAlias("age")
 private long Age;

 @XStreamImplicit(itemFieldName = "address")
 private List addresses = new ArrayList();
 }

 @XStreamAlias("adress")
 public class Address{

 @XStreamAlias("city")
 private String City;

 @XStreamAlias("country")
 private String Country;
 }

主要代码:

FileReader reader = new FileReader("file.xml"); // load file

XStream xstream = new XStream();
xstream.processAnnotations(Person.class);
xstream.processAnnotations(Address.class);

Person person = (Person) xstream.fromXML(reader);

答案 2 :(得分:0)

我相信address会在您的班级Person中引用对象Address。如果是这样,那么你需要这样做:

Person.java

public class Person{
private String name;
    private int age;
    private Address address;
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;}
    public String getcity(){
        return address.getCity();
    }
    public String getCountry(){
        return address.getCountry();
    }
}

Address.java

public class Address {
    private String city;
    private String country;
    public String getCity(){
        return city;
    }
    public String getCountry(){
        return country;
    }
}

JAVA CODE

FileReader xmlReader = new FileReader("file.xml"); // load file

XStream stream = new XStream(new StaxDriver());
stream.alias("person",Person.class);//Since in your xml file `person` is tag

Person person = (Person) stream.fromXML(xmlReader);

System.out.println("Name:"+person.getName()+"\nAge:"+person.getAge()+
           "\nCity:"+person.getCity()+"\nCountry:"+person.getCountry();