Serialization of Java Objects to XML Using XMLEncoder/Decoder
Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network.
At a later time we can transform those bytes back into Java objects. All this is done using java.io.ObjectOutputStream and java.io.ObjectInputStream classes. ObjectOutputStream class provides methods to write primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream.
However, there are problems related to this approach of Serialization of Java objects. Some of them are listed below:
- Logic that saves and restores serialized objects is based on the internal structure of the constituent classes. Any changes to those classes between the time the object was saved and when it was retrieved may cause the deserialization process to fail.
- Versioning problems can occur. If you save an object using one version of the class, but attempt to deserialize it using a newer, different version of the class, deserialization might fail.
Rather than serializing Java objects to binary format we can serialize them to XML documents which is human readable.
Project Structure :
XMLEncoder
java.beans.XMLEncoder works by cloning the object graph and recording the steps that were necessary to create the clone. This way XMLEncoder has a “working copy” of the object graph that mimics the steps XMLDecoder would take to decode the file. Let’s see how to serialize a Java object using XMLEncoder.
Given below is the DVD class which has a List<Movie> as a member.
public class DVD {
private List movies=new ArrayList();
public DVD(){}
public List getMovies() {
return movies;
}
public void setMovies(List movies) {
this.movies = movies;
}
public String toString(){
String movies="";
for(Movie movie:getMovies()){
movies += movie.getName()+", ";
}
return movies;
}
}public class DVD {
private List movies=new ArrayList();
public DVD(){}
public List getMovies() {
return movies;
}
public void setMovies(List movies) {
this.movies = movies;
}
public String toString(){
String movies="";
for(Movie movie:getMovies()){
movies += movie.getName()+", ";
}
return movies;
}
}
Movie class has name, runtime, directors, released year and cast as members.
public class Movie {
private String name;
private int runtime;
private String directors;
private int released;
private String cast;
public Movie(){}public Movie(String name, int runtime, String directors,int released, String cast) {
this.name = name;
this.runtime = runtime;
this.directors = directors;
this.released = released;
this.cast = cast;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRuntime() {
return runtime;
}
public void setRuntime(int runtime) {
this.runtime = runtime;
}
public String getDirectors() {
return directors;
}
public void setDirectors(String directors) {
this.directors = directors;
}
public int getReleased() {
return released;
}
public void setReleased(int released) {
this.released = released;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}}
We want to save DVD object which constitutes List<Movie>. Serializing a DVD object would require serialization of Movie objects also.
Serializing Object to XML
SerializeToXML class has main method which creates four Movie objects. Put them into a List and then set that list as value for DVD instance. Once we have the object to be serialized we create an XMLEncoder instance, then we write that object and call the close method on the encoder instance.
public class SerializeToXML {private static final String SERIALIZED_FILE_NAME="dvd.xml";public static void main(String args[]){Movie bourneIndentity=new Movie("The Bourne Identity",119,"Doug Liman",2002,"Matt Damon, Franka Potente");
Movie bourneSupermacy=new Movie("The Bourne Supremacy",108,"Paul Greengrass",2004,"Matt Damon, Franka Potente, Joan Allen");
Movie bourneUltimatum=new Movie("The Bourne Ultimatum",115,"Paul Greengrass",2007,"Matt Damon, Edgar Ramirez, Joan Allen");
Movie bourneLegacy=new Movie("The Bourne Legacy",135,"Tony Gilroy",2012,"Jeremy Renner, Rachel Weisz, Edward Norton");List moviesList=new ArrayList();
moviesList.add(bourneIndentity);
moviesList.add(bourneSupermacy);
moviesList.add(bourneUltimatum);
moviesList.add(bourneLegacy);DVD bourneSeries=new DVD();
bourneSeries.setMovies(moviesList);XMLEncoder encoder=null;
try{
encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(SERIALIZED_FILE_NAME)));
}catch(FileNotFoundException fileNotFound){
System.out.println("ERROR: While Creating or Opening the File dvd.xml");
}
encoder.writeObject(bourneSeries);
encoder.close();}}
On executing the SerializeToXML class it will serialize the java object to dvd.xml file (In Eclipse IDE you might have to refresh the project to see the newly created dvd.xml file)
< ?xml version="1.0" encoding="UTF-8"?>
< java version="1.7.0_75" class="java.beans.XMLDecoder">
< object class="co.edureka.DVD" id="DVD0">
< void property="movies">
< void method="add">
< object class="co.edureka.Movie">
< void property="cast">
< string>Matt Damon, Franka Potente< /string>
< /void>
< void property="directors">
< string>Doug Liman< /string>
< /void>
< void property="name">
< string>The Bourne Identity< /string>
< /void>
< void property="released">
< int>2002< /int>
< /void>
< void property="runtime">
< int>119< /int>
< /void>
< /object>
< /void>
< void method="add">
< object class="co.edureka.Movie">
< void property="cast">
< string>Matt Damon, Franka Potente, Joan Allen< /string>
< /void>
< void property="directors">
< string>Paul Greengrass< /string>
< /void>
< void property="name">
< string>The Bourne Supremacy< /string>
< /void>
< void property="released">
< int>2004< /int>
< /void>
< void property="runtime">
< int>108< /int>
< /void>
< /object>
< /void>
< void method="add">
< object class="co.edureka.Movie">
< void property="cast">
< string>Matt Damon, Edgar Ramirez, Joan Allen< /string>
< /void>
< void property="directors">
< string>Paul Greengrass< /string>
< /void>
< void property="name">
< string>The Bourne Ultimatum< /string>
< /void>
< void property="released">
< int>2007< /int>
< /void>
< void property="runtime">
< int>115< /int>
< /void>
< /object>
< /void>
< void method="add">
< object class="co.edureka.Movie">
< void property="cast">
< string>Jeremy Renner, Rachel Weisz, Edward Norton< /string>
< /void>
< void property="directors">
< string>Tony Gilroy< /string>
< /void>
< void property="name">
< string>The Bourne Legacy< /string>
< /void>
< void property="released">
< int>2012< /int>
< /void>
< void property="runtime">
< int>135< /int>
< /void>
< /object>
< /void>
< /void>
< /object>
< /java>
Deserializing Object from XML
To get the DVD object back from XML file we will use java.beans.Decoder class.
We create an XMLDecoder instance and call the readObject method. An explicit cast is required as readObject() returns an Object type
public class DeserializeFromXML {
private static final String SERIALIZED_FILE_NAME="dvd.xml";
public static void main(String[] args) {
XMLDecoder decoder=null;
try {
decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream(SERIALIZED_FILE_NAME)));
} catch (FileNotFoundException e) {
System.out.println("ERROR: File dvd.xml not found");
}
DVD bourneSeries=(DVD)decoder.readObject();
System.out.println(bourneSeries);
}
}
Output
We serialized a Java object to an XML document and then deserialized it to get the actual Java object.
Note : We have no-arg constructors in both DVD and Movie class . You will get java.lang.InstantiationException in case no-arg constructor is not present in each class involved in the object graph of the object to be serialized.
If you are interested in trying the code yourself download it:
[buttonleads form_title=”Download Code” redirect_url=https://edureka.wistia.com/medias/jqusavrxbs/download?media_file_id=79202719 course_id=44 button_text=”Download Code”]
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, Python, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series that will explain the various other aspects of Java.
1. Object Oriented Programming
5. Java String
6. Java Array
8. Java Threads
9. Introduction to Java Servlets
11. Exception Handling in Java
12. Java Tutorial
14. Java Programs
15. Kotlin vs Java
16. Dependency Injection Using Spring Boot
22. Socket Programming In Java
25. Library Management System Project in Java
26. Trees in Java
28. Top Data Structures & Algorithms in Java
30. Top 55 Servlet Interview Questions
34. Java Collections Interview Questions and Answers
35. How to Handle Deadlock in Java?
36. Top 50 Java Collections Interview Questions You Need to Know
37. What is the concept of String Pool in Java?
38. What is the difference between C, C++, and Java?
39. Palindrome in Java- How to check a number or string?
40. Top MVC Interview Questions and Answers You Need to Know
41. Top 10 Applications of Java Programming Language
42. Deadlock in Java
43. Square and Square Root in Java
Originally published at ww.edureka.co on September 30, 2021.