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

Detailed introduction to XML serialization and deserialization of Java objects

黄舟
黄舟Original
2017-10-20 09:36:522663browse

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:


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 serialization and deserialization usage demonstration class:


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

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. :


<?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 is generated by the runMultipleObject method and stores the values ​​of 5 SerializableObjects:


<?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>

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:
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