android下xstream转换对象和xml

特意构造一个复杂一些的对象结构,将其转换为xml

@XStreamAlias("group")
public class Group {

    @XStreamAsAttribute
    private String     name;

    private List<User> users;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

}

@XStreamAlias("user")
public class User {
 @XStreamAsAttribute
 private String name;
 private String userName;
 private String password;
 
 @XStreamOmitField
 private Integer age;

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getUserName() {
 return userName;
 }

 public void setUserName(String userName) {
 this.userName = userName;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 public Integer getAge() {
 return age;
 }

 public void setAge(Integer age) {
 this.age = age;
 }
}
XStreamAlias 用来定义xml节点的名字
XStreamAsAttribute 表示此属性是一个属性,而不是子节点
XStreamOmitField 表示忽略此字段
开始转换对象到xml,注意,如果在android下执行不需要xmlpull-1.1.3.1.jar,但是在pc下执行,就需要xmlpull-1.1.3.1.jar,因为PC上的jdk没有pull库

        XStream xstream = new XStream();
        xstream.processAnnotations(Group.class);

        // data set
        Group gourp = new Group();
        gourp.setName("group name");
        User user = new User();
        user.setName("propName");
        user.setUserName("user1");
        user.setPassword("*****");
        List<User> list = new ArrayList<User>();
        list.add(user);
        gourp.setUsers(list);

        String xmlStr = xstream.toXML(gourp);
        System.out.println(xmlStr);
        Group result = (Group)xstream.fromXML(xmlStr);//转换xml到对象



执行结果



<group name="group name">
  <users>
    <user name="propName">
      <userName>user1</userName>
      <password>*****</password>
    </user>
  </users>
</group>

























你可能感兴趣的:(android)