java序列化与反序列化

java序列化与反序列化##

序列化xml

关键的几个类:

javax.xml.bind.JAXBContext

javax.xml.bind.Marshaller

Unmarshaller

需要注意的地方

  1. 这些javabean(c#中的实体类)的时候,由于java没有属性需要自己写set和get方法。在写get和set方法的时候方法名称首单词get和set需要小写,否则会不识别。并且get和set只需要写一个标记就行例如:

     public String getNo() {
            return this._depNo;
     }
     @XmlAttribute(name="班号")
     public void setNo(String NoString) {
            this._depNo=NoString;
     }
    
  2. 另外需要注意的是需要序列化的实体类需要加上@XmlRootElement 标记:

    如:

    @XmlRootElement

    public class department {

主要代码如下:

/**
 * 由实体类转换为xml的demo
 * @return
 */
public static String toXml() {
        String retMsg = "success";

        department d = new department();
        d.setDepName("三年2班");
        d.setNo("01");

        try {
                File file = new File("d:\\file.xml");

                JAXBContext jaxbContext = JAXBContext.newInstance(department.class);
                Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

                jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                jaxbMarshaller.marshal(d, file);
                jaxbMarshaller.marshal(d, System.out);

        } catch (Exception e) {
                e.printStackTrace();
        }
        return retMsg;
}

/**
 * 由xml转换为实体类demo
 * @return
 */
public static department toDep() {
        department d = new department();

        try {
                File file = new File("d:\\file.xml");
                JAXBContext context = JAXBContext.newInstance(department.class);
                Unmarshaller u = context.createUnmarshaller();
                 d = (department) u.unmarshal(file);
        } catch (Exception e) {
                e.printStackTrace();
        }
        return d;
}

Jaxb annotation

补充:在实际使用当中可能需要屏蔽掉不需要显示的属性,或者需要属性排序等。这时就需要用到Jaxb annotation

用法参见: http://blog.csdn.net/a9529lty/article/details/8232932