序列化和反序列化的示例代码

Posted 码上加油站

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化和反序列化的示例代码相关的知识,希望对你有一定的参考价值。

: 需要借助第三方kxml2-2.3.0.jarxmlpull_1_1_3_4c.jar文件

 

public class Student {
   private String sid;
   private String name;
   private int age;
   private double score;
   public String getSid() {
      return sid;
   }
   public void setSid(String sid) {
      this.sid = sid;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   } 
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
     this.age = age;
   }
   public double getScore() {
      return score;
   }
   public void setScore(double score) {
      this.score = score;
   } 
   @Override
   public String toString() {
      return "Student [sid=" + sid + ", name=" + name + ", age=" + age + ", score=" + score + "]";
   }
}

 

 

import java.io.FileOutputStream;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import com.heima.domain.Student;

/**
 * 写入数据
 * @author super
 *
 */

public class PullDemo4 {
   public static void main(String[] args) throws Exception {
      Student stu = new Student();
      stu.setSid("s003");
      stu.setName("赵六");
      stu.setAge(66);
      stu.setScore(66.6);

      //1.创建解析器工厂
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
      //2.获取解析器
      XmlSerializer serializer = factory.newSerializer();
       //3.设置输出流
      serializer.setOutput(new FileOutputStream("s.xml"), "utf-8");
      //4.写入文档声明
      serializer.startDocument("utf-8", true);
      serializer.startTag(null, "students");
      serializer.startTag(null, "student");
      serializer.attribute(null, "sid", stu.getSid());
      serializer.startTag(null, "name");
      serializer.text(stu.getName());
      serializer.endTag(null, "name");     
      serializer.startTag(null, "age");
      serializer.text(String.valueOf(stu.getAge()));
      serializer.endTag(null, "age");
      serializer.startTag(null, "score");
      serializer.text(String.valueOf(stu.getScore()));
      serializer.endTag(null, "score");   
      serializer.endTag(null, "student");
      serializer.endTag(null, "students");
      //写入结束文档
      serializer.endDocument();
   }

}

 

 

以上是关于序列化和反序列化的示例代码的主要内容,如果未能解决你的问题,请参考以下文章

Kafka消息序列化和反序列化

Kafka 消息序列化和反序列化(上)

C++中的序列化和反系列化

C++中的序列化和反系列化

将 Objective-C 对象序列化和反序列化为 JSON

序列化和反序列化代码