• 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

  • 相关阅读:
    用Python完成Excel的常用操作
    用Python实现excel 14个常用操作
    ubuntu and centos各种上网代理设置
    vim 熟练度练习
    Ansible-playbook 使用方式 看一篇就够了
    python 使用ldap3 查询跨域的用户信息
    python pyinstaller 的使用
    vs code新建python虚拟环境
    vs code 远程开发环境设置
    上下文管理器(Context Manager)
  • 原文地址:https://www.cnblogs.com/falcon-fei/p/5193049.html
Copyright © 2020-2023  润新知