zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    java学习day2--java和javac命令的使用
    java学习day1--了解java及JDK环境变量的配置
    idea 修改console 日志区的背景
    微信的storage的操作
    python 基础
    shiro标签说明
    IDEA 修改编辑区的背景颜色
    java注解
    java的反射
    创建一个maven项目
  • 原文地址:https://www.cnblogs.com/falcon-fei/p/5193049.html
Copyright © 2011-2022 走看看