Java-XML反序列化Object 及Object序列化为XML

    技术2026-05-08  1

    注:有位群友在群里贴了一段C#的XML/Object之间序列化代码,本猫解的不错,花了点时间,做了个Java的,依本猫的记性,不用多久就忘了,放在Blog上存着吧 ^_^UserBean和OtherUserInfoBean就是一个set/get的bean类,造个就行了.package org.sl.bean;import java.beans.XMLDecoder;import java.beans.XMLEncoder;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.Serializable;public class ObjectXmlSerial {       public static void main(String[] args) throws IOException{        UserBean user = new UserBean();        OtherUserInfoBean otherUserInfo = new OtherUserInfoBean();               otherUserInfo.setAddress("汉字");        otherUserInfo.setEmail("test@test.com");               user.setName("hello");        user.setPassword("world");               user.setOtherUserInfo(otherUserInfo);                                 ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();        BufferedOutputStream bufferOut = new BufferedOutputStream(byteArrayOut);               writeObjectToXML(bufferOut, user);        byte[] bys = byteArrayOut.toByteArray();               byteArrayOut.close();        bufferOut.close();                      ByteArrayInputStream byteArrayIn = new ByteArrayInputStream(bys);        BufferedInputStream bufferIn = new BufferedInputStream(byteArrayIn);               UserBean user1 = readObjectFromXML(bufferIn);               byteArrayIn.close();        bufferIn.close();                      System.out.println(user1.getName());        System.out.println(user1.getOtherUserInfo().getAddress());    }       public static <T extends Serializable> void writeObjectToXML(OutputStream out, T obj){        XMLEncoder xmlEncoder = null;               try{            xmlEncoder = new XMLEncoder(out);            xmlEncoder.writeObject(obj);        }finally{            if(null != xmlEncoder)                xmlEncoder.close();        }    }       @SuppressWarnings("unchecked")    public static <T extends Serializable> T readObjectFromXML(InputStream in){        T obj = null;        XMLDecoder xmlDecoder = null;               try{            xmlDecoder = new XMLDecoder(in);            obj = (T) xmlDecoder.readObject();        }finally{            if(null != xmlDecoder)                xmlDecoder.close();        }        return obj;    }}

    最新回复(0)