Home » Blog » Serializing Java Objects to XML and Deserializing XML back to Java Objects

Share This Post

Console / Console Applications / Java / Main Slider / Tutorial

Serializing Java Objects to XML and Deserializing XML back to Java Objects

Morse Code Medphor

Like object serialization this is very easy and straight forward. Below is two examples of psuedo code for writing and then reading. This code merely shows the steps. We didn’t have to use the buffered streams. With small files you do not have to but with larger files it will speed up reading and writing.

XMLEncoder Class

//psuedo code does not run
import java.beans.*;
import java.io.*;

public class SerializeToXML {
 public static void main(String args[]){
  // an object, composition of objects or collection of objects
  AnObject anObject = new AnObject();
  XMLEncoder encoder=null;
  try{
   encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("objects.xml")));
  }catch(FileNotFoundException fnfe){
   fnfe.printStackTrace();
  }
  encoder.writeObject(anObject);
  encoder.close();
 }
}
//psuedo code does not run
import java.beans.*;
import java.io.*;

public class DeserializeFromXML {
 public static void main(String[] args) {
  XMLDecoder decoder=null;
  try {
   decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream("objects.xml")));
  } catch (FileNotFoundException fnfe) {
   fnfe.printStackTrace();
  }
  AnObject anObject=(AnObject)decoder.readObject();
  System.out.println(anObject);
 }
}

Serialize Java Objects to XML

First let me say that My example was made similar to this guys example https://www.edureka.co/blog/serialization-of-java-objects-to-xml-using-xmlencoder-decoder/.

His example had an error, he was missing some generics code <Movie> at least in the DVD object.

I entered the code below first using inner classes for JournalEntry and didn’t use the Journal object. I had Exceptions on each JournalEntry in the ArrayList. So I first Made Journal object with only List field. It still didn’t work. Then I moved the inner class outside. It seemed to work. But nothing much was in the journal.xml file. So I added toString methods.  Still nothing in the journal.xml file. Then I added getters and setters. Viola, it worked. I’m still not sure of all that what exactly was necessary.

import java.util.*;
import java.beans.*;
import java.io.*;

public class SerializeToXML {	
 ArrayList<JournalEntry> entries = new ArrayList<JournalEntry>();
 public SerializeToXML(){
  JournalEntry anEntry = new JournalEntry();
  anEntry.date=new Date("10/2/18");
  anEntry.creditNote="Food order in";
  anEntry.debitNote="Pizza";
  anEntry.creditAccount=100;
  anEntry.debitAccount=500;
  anEntry.amount=17.95f;
  entries.add(anEntry);
  anEntry = new JournalEntry();
  anEntry.date=new Date("10/2/18");
  anEntry.creditNote="Tip order in";
  anEntry.debitNote="Pizza tip";
  anEntry.creditAccount=100;
  anEntry.debitAccount=501;
  anEntry.amount=4.0f;
  entries.add(anEntry);
  anEntry = new JournalEntry();
  anEntry.date=new Date("10/5/18");
  anEntry.creditNote="Credit Card Payment";
  anEntry.debitNote="Oct Payment";
  anEntry.creditAccount=100;
  anEntry.debitAccount=310;
  anEntry.amount=100.00f;
  entries.add(anEntry);
  anEntry = new JournalEntry();
  anEntry.date=new Date("10/7/18");
  anEntry.creditNote="Denny's Work Check";
  anEntry.debitNote="Pay Check";
  anEntry.creditAccount=400;
  anEntry.debitAccount=100;
  anEntry.amount=420.37f;
  entries.add(anEntry);
  Journal aJournal=new Journal();
  aJournal.journal=entries;
  XMLEncoder encoder=null;
  try{
   encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("journal.xml")));
  }catch(FileNotFoundException fnfe){
   fnfe.printStackTrace();
  }
  encoder.writeObject(aJournal);
  encoder.close();
 }
 public static void main(String args[]){
  new SerializeToXML();
 } 
}
import java.util.*;

import java.util.*;

public class JournalEntry{
  Date date=null;
  String creditNote="";
  String debitNote="";
  int creditAccount=0;
  int debitAccount=0;
  float amount=0.0f;
  public void setDate(Date date){
   this.date=date;
  }
  public void setCreditNote(String creditNote){
   this.creditNote=creditNote;
  }
  public void setDebitNote(String debitNote){
   this.debitNote=debitNote;
  }
  public void setCreditAccount(int creditAccount){
   this.creditAccount=creditAccount;
  }
  public void setDebitAccount(int debitAccount){
   this.debitAccount=debitAccount;
  }
  public void setAmount(float amount){
   this.amount=amount;
  }
  public Date getDate(){
   return date;
  }
  public String getCreditNote(){
   return creditNote;
  }
  public String getDebitNote(){
   return debitNote;
  }
  public int getCreditAccount(){
   return creditAccount;
  }
  public int getDebitAccount(){
   return debitAccount;
  }
  public float getAmount(){
   return amount;
  }
 }
import java.util.*;

public class Journal{
  List<JournalEntry> journal = new ArrayList<JournalEntry>();
  public void setJournal(List<JournalEntry> journal){
   this.journal=journal;
  }
  public List<JournalEntry> getJournal(){
   return journal;
  }
  public String toString(){
  String journalString="";
  for(JournalEntry entry:journal){
   journalString += entry.date+" \n";
   journalString += entry.creditNote+":";
   journalString += entry.creditAccount+" \n";
   journalString += entry.debitNote+":";
   journalString += entry.debitAccount+" \n";
    journalString += entry.amount+" \n\n";
  }
  return journalString; 
 }
}

XML Output

Here is the XML produced.

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_161" class="java.beans.XMLDecoder">
 <object class="Journal" id="Journal0">
  <void property="journal">
   <void method="add">
    <object class="JournalEntry">
     <void property="amount">
      <float>17.95</float>
     </void>
     <void property="creditAccount">
      <int>100</int>
     </void>
     <void property="creditNote">
      <string>Food order in</string>
     </void>
     <void property="date">
      <object class="java.util.Date">
       <long>1538456400000</long>
      </object>
     </void>
     <void property="debitAccount">
      <int>500</int>
     </void>
     <void property="debitNote">
      <string>Pizza</string>
     </void>
    </object>
   </void>
   <void method="add">
    <object class="JournalEntry">
     <void property="amount">
      <float>4.0</float>
     </void>
     <void property="creditAccount">
      <int>100</int>
     </void>
     <void property="creditNote">
      <string>Tip order in</string>
     </void>
     <void property="date">
      <object class="java.util.Date">
       <long>1538456400000</long>
      </object>
     </void>
     <void property="debitAccount">
      <int>501</int>
     </void>
     <void property="debitNote">
      <string>Pizza tip</string>
     </void>
    </object>
   </void>
   <void method="add">
    <object class="JournalEntry">
     <void property="amount">
      <float>100.0</float>
     </void>
     <void property="creditAccount">
      <int>100</int>
     </void>
     <void property="creditNote">
      <string>Credit Card Payment</string>
     </void>
     <void property="date">
      <object class="java.util.Date">
       <long>1538715600000</long>
      </object>
     </void>
     <void property="debitAccount">
      <int>310</int>
     </void>
     <void property="debitNote">
      <string>Oct Payment</string>
     </void>
    </object>
   </void>
   <void method="add">
    <object class="JournalEntry">
     <void property="amount">
      <float>420.37</float>
     </void>
     <void property="creditAccount">
      <int>400</int>
     </void>
     <void property="creditNote">
      <string>Denny&apos;s Work Check</string>
     </void>
     <void property="date">
      <object class="java.util.Date">
       <long>1538888400000</long>
      </object>
     </void>
     <void property="debitAccount">
      <int>100</int>
     </void>
     <void property="debitNote">
      <string>Pay Check</string>
     </void>
    </object>
   </void>
  </void>
 </object>
</java>

 

Deserializing XML back to Java Objects

Here is the deserialization code below and the results of running both with console debug output.

import java.beans.*;
import java.io.*;

public class DeserializeFromXML{
 public static void main(String[] args) {
  XMLDecoder decoder=null;
  try {
   decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream("journal.xml")));
  } catch (FileNotFoundException fnfe) {
   fnfe.printStackTrace();
  }
  Journal journal=(Journal)decoder.readObject();
  System.out.println(journal);
 }
}

 

c:\dev\java\arksoft\post\files>java SerializeToXML
Tue Oct 02 00:00:00 CDT 2018
Food order in:100
Pizza:500
17.95

Tue Oct 02 00:00:00 CDT 2018
Tip order in:100
Pizza tip:501
4.0

Fri Oct 05 00:00:00 CDT 2018
Credit Card Payment:100
Oct Payment:310
100.0

Sun Oct 07 00:00:00 CDT 2018
Denny's Work Check:400
Pay Check:100
420.37
c:\dev\java\arksoft\post\files>java DeserializeFromXML
Tue Oct 02 00:00:00 CDT 2018
Food order in:100
Pizza:500
17.95

Tue Oct 02 00:00:00 CDT 2018
Tip order in:100
Pizza tip:501
4.0

Fri Oct 05 00:00:00 CDT 2018
Credit Card Payment:100
Oct Payment:310
100.0

Sun Oct 07 00:00:00 CDT 2018
Denny's Work Check:400
Pay Check:100
420.37

 

Share This Post

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>