java – 如何使用XStream将对象列表转换为XML文档

如何使用XStream将对象列表转换为XML文档?

以及如何反序列化?

这是我的xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>  
  <fullname>Guilherme</fullname>
  <age>10</age>
  <address>address,address,address,address,</address>
</person>
<person>  
  <fullname>Guilherme</fullname>
  <age>10</age>
  <address>address,address,address,address,</address>
</person>
</persons>

Person bean包含3个字段,如何使用自定义转换器将其转换回Bean List?

最佳答案
您不一定需要CustomConverter.

你需要一个类来保存你的列表:

public class PersonList {

    private List<Person> list;

    public PersonList(){
        list = new ArrayList<Person>();
    }

    public void add(Person p){
        list.add(p);
    }
}

将列表序列化为XML:

    XStream xstream = new XStream();
    xstream.alias("person", Person.class);
    xstream.alias("persons", PersonList.class);
    xstream.addImplicitCollection(PersonList.class, "list");

    PersonList list = new PersonList();
    list.add(new Person("ABC",12,"address"));
    list.add(new Person("XYZ",20,"address2"));

    String xml = xstream.toXML(list);

将xml反序列化为个人对象列表:

    String xml = "<persons><person>...</person></persons>";
    PersonList pList = (PersonList)xstream.fromXML(xml);

转载注明原文:java – 如何使用XStream将对象列表转换为XML文档 - 代码日志