Java对象的XML序列化与反序列化实例解析

时间:2022-11-19 08:51:30

上一篇文章我们介绍了java实现的各种排序算法代码示例,本文我们看看Java对象的xml序列化反序列化的相关内容,具体如下。

XML是一种标准的数据交换规范,可以方便地用于在应用之间交换各类数据。如果能在Java对象和XML文档之间建立某种映射,例如Java对象的XML序列化和反序列化,那么就可以使Java的对象方便地与其他应用进行交换。

java.beans包里面有两个类XMLEncoder和Decoder,分别用于将符合JabaBeans规范的Java对象以XML方式序列化和反序列化。以下代码显示了如何使用这两个类实现Java对象的XML编码和解码。

待序列化的Java类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.Serializable;
public class SerialableObject implements Serializable
{
    private static final long serialVersionUID = 8745578444312339136L;
    public SerialableObject()
      {
    }
    public SerialableObject(int id, String name, double value)
      {
        this.id = id;
        this.name = name;
        this.value = value;
    }
    public int getId()
      {
        return id;
    }
    public void setId(int id)
      {
        this.id = id;
    }
    public String getName()
      {
        return name;
    }
    public void setName(String name)
      {
        this.name = name;
    }
    public double getValue()
      {
        return value;
    }
    public void setValue(double value)
      {
        this.value = value;
    }
    private int id;
    private String name;
    private double value;
}

XML序列化和反序列化用法演示类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Vector;
public class XmlSerialize
{
    public XmlSerialize()
      {
    }
    public void serializeSingleObject(OutputStream os, Object obj)    // 序列化单个java对象
    {
        // XMLEncoder xe = new XMLEncoder(os);
        XMLEncoder xe = new XMLEncoder(os, "GBK", true, 0);
        // 仅用于Java SE 7
        xe.writeObject(obj);
        // 序列化成XML字符串
        xe.close();
    }
    public Object deserializeSingleObject(InputStream is)    // 反序列化单个Java对象
    {
        XMLDecoder xd = new XMLDecoder(is);
        Object obj = xd.readObject();
        // 从XML序列中解码为Java对象
        xd.close();
        return obj;
    }
    public void serializeMultipleObject(OutputStream os, List<Object> objs)    // 序列化多个Java对象
    {
        XMLEncoder xe = new XMLEncoder(os);
        xe.writeObject(objs);
        // 序列化成XML字符串
        xe.close();
    }
    public List<Object> deserializeMultipleObject(InputStream is)    // 反序列化多个Java对象
    {
        XMLDecoder xd = new XMLDecoder(is);
        @SuppressWarnings("unchecked")
           List<Object> objs = (List<Object>)xd.readObject();
        // 从XML序列中解码为Java对象列表
        xd.close();
        return objs;
    }
    public void runSingleObject()
      {
        File xmlFile = new File("object.xml");
        SerialableObject jo4Out = new SerialableObject(1, "Java序列化为XML", 3.14159265359);
        // 创建待序列化的对象
        try
           {
            FileOutputStream ofs = new FileOutputStream(xmlFile);
            // 创建文件输出流对象
            serializeSingleObject(ofs, jo4Out);
            ofs.close();
        }
        catch (FileNotFoundException e)
           {
            e.printStackTrace();
        }
        catch (IOException e)
           {
            e.printStackTrace();
        }
        try
           {
            FileInputStream ifs = new FileInputStream(xmlFile);
            SerialableObject jo4In = (SerialableObject)deserializeSingleObject(ifs);
            System.out.println("id: " + jo4In.getId());
            System.out.println("name: " + jo4In.getName());
            System.out.println("value: " + jo4In.getValue());
        }
        catch (FileNotFoundException e)
           {
            e.printStackTrace();
        }
    }
    public void runMultipleObject()
      {
        File xmlFile = new File("objects.xml");
        List<SerialableObject> sos4Out = new Vector<SerialableObject>();
        sos4Out.add(new SerialableObject(1, "Java序列化为XML - 1", 3.14));
        // 创建待序列化的对象
        sos4Out.add(new SerialableObject(2, "Java序列化为XML - 2", 3.14159));
        // 创建待序列化的对象
        sos4Out.add(new SerialableObject(3, "Java序列化为XML - 3", 3.1415926));
        // 创建待序列化的对象
        sos4Out.add(new SerialableObject(4, "Java序列化为XML - 4", 3.141592653));
        // 创建待序列化的对象
        sos4Out.add(new SerialableObject(5, "Java序列化为XML - 5", 3.14159265359));
        // 创建待序列化的对象
        try
           {
            FileOutputStream ofs = new FileOutputStream(xmlFile);
            // 创建文件输出流对象
            serializeSingleObject(ofs, sos4Out);
            ofs.close();
        }
        catch (FileNotFoundException e)
           {
            e.printStackTrace();
        }
        catch (IOException e)
           {
            e.printStackTrace();
        }
        try
           {
            FileInputStream ifs = new FileInputStream(xmlFile);
            @SuppressWarnings("unchecked")
                 List<SerialableObject> sos4In = (List<SerialableObject>)deserializeSingleObject(ifs);
            for (SerialableObject jo4In : sos4In)
                 {
                System.out.println("id: " + jo4In.getId());
                System.out.println("name: " + jo4In.getName());
                System.out.println("value: " + jo4In.getValue());
            }
        }
        catch (FileNotFoundException e)
           {
            e.printStackTrace();
        }
    }
    public static void main(String[] args)
      {
        XmlSerialize xs = new XmlSerialize();
        xs.runSingleObject();
        xs.runMultipleObject();
    }
}

需要注意的是,待序列化的类必须要符合JavaBeans的格式规范,即:具有一个无参的public构造函数,所有数据成员的访问均采用getter/setter模式,此外,这个类必须是public的,并且实现了java.io.Serializable接口。

程序运行之后,会产生两个文件:

object.xml是runSingleObject方法生成的,存放了单个的SerialableObject的值:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="GBK"?>
<java version="1.7.0" class="java.beans.XMLDecoder">
 <object class="SerialableObject">
 <void property="id">
  <int>1</int>
 </void>
 <void property="name">
  <string>Java序列化为XML</string>
 </void>
 <void property="value">
  <double>3.14159265359</double>
 </void>
 </object>
</java>

objects.xml是runMultipleObject方法产生的,存放了5个SerializableObject的值:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?xml version="1.0" encoding="GBK"?>
<java version="1.7.0" class="java.beans.XMLDecoder">
 <object class="java.util.Vector">
 <void method="add">
  <object class="SerialableObject">
  <void property="id">
   <int>1</int>
  </void>
  <void property="name">
   <string>Java序列化为XML - 1</string>
  </void>
  <void property="value">
   <double>3.14</double>
  </void>
  </object>
 </void>
 <void method="add">
  <object class="SerialableObject">
  <void property="id">
   <int>2</int>
  </void>
  <void property="name">
   <string>Java序列化为XML - 2</string>
  </void>
  <void property="value">
   <double>3.14159</double>
  </void>
  </object>
 </void>
 <void method="add">
  <object class="SerialableObject">
  <void property="id">
   <int>3</int>
  </void>
  <void property="name">
   <string>Java序列化为XML - 3</string>
  </void>
  <void property="value">
   <double>3.1415926</double>
  </void>
  </object>
 </void>
 <void method="add">
  <object class="SerialableObject">
  <void property="id">
   <int>4</int>
  </void>
  <void property="name">
   <string>Java序列化为XML - 4</string>
  </void>
  <void property="value">
   <double>3.141592653</double>
  </void>
  </object>
 </void>
 <void method="add">
  <object class="SerialableObject">
  <void property="id">
   <int>5</int>
  </void>
  <void property="name">
   <string>Java序列化为XML - 5</string>
  </void>
  <void property="value">
   <double>3.14159265359</double>
  </void>
  </object>
 </void>
 </object>
</java>

总结

以上就是本文关于Java对象的XML序列化与反序列化实例解析的全部内容,希望对大家有所帮助。什么问题可以随时留言,小编会及时回复大家的。

原文链接:http://blog.csdn.net/kingfox/article/details/8087103