Home Java javaTutorial Detailed introduction to XML serialization and deserialization of Java objects

Detailed introduction to XML serialization and deserialization of Java objects

Oct 20, 2017 am 09:36 AM
java Serialization

This article mainly introduces the XML serialization and deserialization example analysis of Java objects. The editor thinks it is quite good, so I will share it with you here.

In the previous article, we introduced code examples of various sorting algorithms implemented in Java. In this article, we look at the relevant content of XML serialization and deserialization of Java objects, as follows.

XML is a standard data exchange specification that can be easily used to exchange various types of data between applications. If a certain mapping can be established between Java objects and XML documents, such as XML serialization and deserialization of Java objects, then Java objects can be easily exchanged with other applications.

There are two classes XMLEncoder and Decoder in the java.beans package, which are used to serialize and deserialize Java objects that comply with the JabaBeans specification in XML. The following code shows how to implement XML encoding and decoding of Java objects using these two classes.

Java class to be serialized:


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;

}

Copy after login

XML serialization and deserialization usage demonstration class:


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();

    }

}

Copy after login

It should be noted that the class to be serialized must comply with the JavaBeans format specification, that is: it has a public constructor with no parameters, and access to all data members is Adopt the getter/setter pattern. In addition, this class must be public and implement the java.io.Serializable interface.

After the program is run, two files will be generated:

object.xml is generated by the runSingleObject method and stores the value of a single 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>

Copy after login

objects.xml is generated by the runMultipleObject method and stores the values ​​of 5 SerializableObjects:


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>

Copy after login

Summarize

The above is the detailed content of Detailed introduction to XML serialization and deserialization of Java objects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles