XStream

官网地址:XStream

Maven

<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
	<groupId>com.thoughtworks.xstream</groupId>
	<artifactId>xstream</artifactId>
	<version>1.4.10</version>
</dependency>

初始化XStream

XStream xstream = new XStream();

指定别名

// 类
xstream.alias("student", Student.class);
// 字段
xstream.aliasField("name", Student.class, "studentName");
// 隐式集合
xstream.addImplicitCollection(Student.class, "notes");
// 属性
xstream.useAttributeFor(Student.class, "studentName");
xstream.aliasField("name", Student.class, "studentName");
// 包
xstream.aliasPackage("my.company.xstream", "com.yiibai.xstream");

注解

使用注解前,需要先设置XStream

xstream.processAnnotations(Note.class);
    或
xstream.autodetectAnnotations(true);
// 类、字段
@XStreamAlias("student")
// 隐式集合
@XStreamImplicit
// 属性
@XStreamAlias("name")
@XStreamAsAttribute

对象流

ObjectOutputStream objectOutputStream = xstream.createObjectOutputStream(new FileOutputStream("test.txt"));
objectOutputStream.writeObject(student1);
objectOutputStream.writeObject(student2);
objectOutputStream.writeObject(student3);
objectOutputStream.writeObject(student4);
objectOutputStream.writeObject("Hello World");
objectOutputStream.close();

ObjectInputStream objectInputStream = xstream.createObjectInputStream(new FileInputStream("test.txt"));
Student student5 = (Student) objectInputStream.readObject();
Student student6 = (Student) objectInputStream.readObject();
Student student7 = (Student) objectInputStream.readObject();
Student student8 = (Student) objectInputStream.readObject();
String text = (String) objectInputStream.readObject();
System.out.println(student5);
System.out.println(student6);
System.out.println(student7);
System.out.println(student8);
System.out.println(text);

自定义转换器

使用前需要设置XStream:

xstream.registerConverter(new StudentConverter());

示例:

class StudentConverter implements Converter {

	public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
		Student student = (Student) value;
		writer.startNode("name");
		writer.setValue(student.getName().getFirstName() + "," + student.getName().getLastName());
		writer.endNode();
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		reader.moveDown();
		String[] nameparts = reader.getValue().split(",");
		Student student = new Student(nameparts[0], nameparts[1]);
		reader.moveUp();
		return student;
	}

	public boolean canConvert(Class object) {
		return object.equals(Student.class);
	}
}

canConvert - 检查支持的对象类型的序列化。
marshal - 序列化对象到XML。
unmarshal - 从XML对象反序列化

解决控制台报错Security framework of XStream not initialized, XStream is probably vulnerable.

XStream.setupDefaultSecurity(xstream);

解决com.thoughtworks.xstream.security.ForbiddenClassException异常

Class<?>[] classes = new Class[] { Student.class, Note.class };
xstream.allowTypes(classes);

参考资料

posted @ 2018-06-28 16:18  流星<。)#)))≦  阅读(2522)  评论(0编辑  收藏  举报