Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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. It is a crucial concept to learn for earning your Java certification.
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:
Rather than serializing Java objects to binary format we can serialize them to XML documents which is human readable.
Project Structure :
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; } }
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); } }
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”]
Got a question for us? Please mention it in the comments section and we will get back to you.
Related Posts:
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 7th December,2024 7th December SAT&SUN (Weekend Batch) | View Details |
edureka.co
I had to correct a generics error with the List objects in DVD needed
Movie movie:getMovies() -> its making a error i think its the java version, this code was made for java 1.7 and i have java 1.8.0111.
public String toString(){
String movies=””;
for(Movie movie:getMovies()){
moviess += movie.getName()+”, “;
}
return movies;}
Hey Antonio, thanks for checking out our blog. Please try this:
public String toString(){
String movies=””;
for(Movie movie:ObjectArrayName){
movies += movie.getName()+”, “;
}
return movies;
}
Hope this helps. Cheers!
Hi I a problem regarding the XMLDecoder,
Using the encoder I had created few xml files that were generated using java7
Now that I have migrated the project to Java8 I am not able to read the XML due to the java version dependency there in the xml.
How do I make the class neglect the java version used