import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; /** * JAVA序列化和反序列化->XML * <p> *公共无参构造函数。 * </p> * */ public class SerializableXmlUtils { @SuppressWarnings("unchecked") public static <T> T parserXML(String xml) { ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes()); XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in)); decoder.close(); return (T) decoder.readObject(); } public static <T> String formatXML(T entity) { ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(out)); encoder.writeObject(entity); encoder.close(); return out.toString(); } public static void main(String[] args) throws Exception { User user = new User(); user.setId(1); user.setName("张三"); user.setAihao(new String[] { "球", "球2" }); user.setStudent(new Student(1, "er")); String xml = formatXML(user); System.out.println("序列化到XML:\n" + xml); user = parserXML(xml); System.out.println("反序列化Bean:\n" + user); } }
主要是 java.beans包下的对称序列化,有点类似URL Decoder/Encoder
原文地址:https://www.cnblogs.com/hai77haidong/p/8624455.html
时间: 2024-11-09 17:14:27