Five Minute Tutorial

Version 2 by Robin Shen
on Feb 10, 2010 04:10.


compared with
Version 3 by Robin Shen
on Feb 10, 2010 04:25.


Key
These lines were removed. This word was removed.
These lines were added. This word was added.

View page history


There are 1 changes. View first change.

 We demonstrate usage of this tool with a simple tutorial. Assume a _Task_ class below with a _prioritized_ field indicating whether it is a prioritized task:
 {code}
 package example;
  
 public class Task {
  public boolean prioritized;
 }
 {code}
 With XStream, we can serialize object of this class to XML like below:
 {code}
 Task task = new Task();
 task.setPrioritized(true);
 String xml = new XStream().toXML(task);
 saveXmlToFileOrDatabase(xml);
 {code}
 Resulting XML will be:
 {code}
 <example.Task>
  <prioritized>true</prioritized>
 </example.Task>
 {code}
 And you can deserialize the XML to get back task object:
 {code}
 String xml = readXmlFromFileOrDatabase();
 Task task = (Task)(new XStream(new DomDriver()).fromXML(xml));
 {code}
  Everything is fine. Now we find a prioritized flag is not enough for a task, we need to enhance it to take a numeric priority field ranges from 1 to 10, so the task class becomes:
  Everything is fine. Now we find a prioritized flag is not enough, so we enhance the Task class to use a numeric priority field ranging from 1 to 10:
 {code}
 package example;
  
 public class Task {
  public int priority;
 }
 {code}
 However deserialization of previously saved xml is no longer possible since the new Task class is no longer compatible.