XSream转换实体类,下划线不能成功转换?

题目描述

题目来源及自己的思路

相关代码

实体类

@Data

@XStreamAlias("student")

public class Students {

@XStreamAlias("name")

@XStreamAsAttribute

private String name;

@XStreamAlias("age")

@XStreamAsAttribute

private String age;

@XStreamAlias("mrch_id")

@XStreamAsAttribute

private String mrchId;

}

转化工具和测试

public class XstreamUtil {

public static final String XmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";

public static Object toXml(Class<?> clazz, Object obj){

Object xmlObject = null;

//不对特殊字符进行转换,防止双下划线问题

XStream xStream = new XStream(new Xpp3Driver(new NoNameCoder()));

//使用传过来类的注解

xStream.processAnnotations(clazz);

//自动检测注解

xStream.autodetectAnnotations(true);

//序列化对象到xml

xmlObject = xStream.toXML(obj);

return XmlHeader + xmlObject;

}

public static Object toBean(Class<?> clazz, String xml) {

Object xmlObject = null;

XStream xstream = new XStream();

//由于对象默认开启安全防护,添加这条语句解决问题。尽量限制最低权限。防止com.thoughtworks.xstream.security.ForbiddenClassException

xstream.addPermission(AnyTypePermission.ANY);

xstream.processAnnotations(clazz);

xstream.autodetectAnnotations(true);

xmlObject= xstream.fromXML(xml);

return xmlObject;

}

public static void main(String[] args) {

Students students = new Students();

students.setAge("15");

students.setName("张三");

students.setMrchId("ssss");

Object o = toXml(Students.class, students);

System.out.println(o);

Students o1 =(Students) toBean(Students.class,(String) o);

System.out.println(o1);

}

}

结果:
<?xml version="1.0" encoding="UTF-8"?>
<student name="张三" age="15" mrch_id="ssss"/>
Students(name=张三, age=15, mrchId=null)

以上是 XSream转换实体类,下划线不能成功转换? 的全部内容, 来源链接: utcz.com/p/944784.html

回到顶部