<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.17</version> </dependency> import com.thoughtworks.xstream.XStream; import java.io.*; public class SerializationExample { public static void main(String[] args) { XStream xstream = new XStream(); XStream.setupDefaultSecurity(xstream); xstream.allowTypes(new Class[] {MyClass.class}); xstream.alias("my-object", MyClass.class); MyClass obj = new MyClass("John", 25); String xml = xstream.toXML(obj); try (FileWriter writer = new FileWriter("object.xml")) { writer.write(xml); } catch (IOException e) { e.printStackTrace(); } try (BufferedReader reader = new BufferedReader(new FileReader("object.xml"))) { StringBuilder xmlContent = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { xmlContent.append(line); } MyClass newObj = (MyClass)xstream.fromXML(xmlContent.toString()); System.out.println("Name: " + newObj.getName()); System.out.println("Age: " + newObj.getAge()); } catch (IOException e) { e.printStackTrace(); } } } class MyClass { private String name; private int age; public MyClass(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }


上一篇:
下一篇:
切换中文