java xml 与 class 转换

User类

package com.bean;

 

import com.thoughtworks.xstream.annotations.XStreamAlias;

 

import lombok.Data;

 

@Data

@XStreamAlias("Struct")

public class User {

@XStreamAlias("USER_NAME")

private String name;

@XStreamAlias("USER_SEX")

private String sex;

@XStreamAlias("USER_AGE")

private int age;

 

}

 

UserPad类

 

package com.bean;

 

import java.util.List;

 

import com.thoughtworks.xstream.annotations.XStreamAlias;

 

import lombok.Data;

 

@Data

@XStreamAlias("Body")

public class UserPad {

@XStreamAlias("HAHA")

private String hello;

@XStreamAlias("USER_ARRAY_LIST")

private List<User> userList;

}

测试类

package com.Test;

 

import java.util.ArrayList;

import java.util.List;

 

import com.bean.User;

import com.bean.UserPad;

import com.thoughtworks.xstream.XStream;

import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

import com.thoughtworks.xstream.io.xml.XppDriver;

 

public class TestDemo1 {

public static void main(String[] args) throws Exception{

User user ;

UserPad up = new UserPad();

List<User> userList = new ArrayList<User>();

user = new User();

user.setName("张三");

user.setSex("男");

user.setAge(20);

userList.add(user);

user = new User();

user.setName("张三1");

user.setSex("男");

user.setAge(22);

userList.add(user);

user = new User();

user.setName("张三2");

user.setSex("女");

user.setAge(25);

userList.add(user);

up.setUserList(userList);

up.setHello("测试属性");

XStream xs = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));

xs.processAnnotations(UserPad.class);

xs.aliasSystemAttribute(null, "class");

xs.alias("Body", UserPad.class);

String xmlResp = xs.toXML(up);

System.out.println(xmlResp);

XStream xss = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-","_"))); // 处理注解的下划线

xss.processAnnotations(UserPad.class);

Object obj = xss.fromXML(xmlResp);

System.out.println(obj);

 

XStream xs1 = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));

xs1.processAnnotations(UserPad.class);

xs1.aliasSystemAttribute(null, "class");

xs1.alias("Body", Object.class);

String xmlResp1 = xs1.toXML(obj);

System.out.println(xmlResp1);

}

 

posted @ 2020-11-18 19:09  米豪  阅读(408)  评论(0编辑  收藏  举报