I serialize my domainObjects using XStream.
I would like to add some kind of versioning information to a generated xml file just in case my domain model changes.
Is there a way to do it using xstream ?
I vould prefer a parameter named "version" in a root tag (<object-stream>
) but anything else would be good too.
Thanks in advance.
For most use cases, the XStream instance is thread-safe, once configured (there are caveats when using annotations) Clear messages are provided during exception handling to help diagnose issues. Starting with version 1.4.
XStream's primary purpose is for serialization. It allows existing Java objects to be converted to clean XML and then restored again, without modifications. This is particularly useful as a form of persistence (no complicated database mappings required) or for sending objects over the wire.
XStream is a simple library to serialize objects to XML and back again. It does not require any mapping, and generates clean XML. For more information on XStream, refer to the XStream web site. The Spring integration classes reside in the org. springframework.
you can register your converter that adds the desired versioning tag to your root element
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class PersonConverter implements Converter {
public boolean canConvert(Class clazz) {
return clazz.equals(Person.class);
}
public void marshal(Object value,
HierarchicalStreamWriter writer,
MarshallingContext context) {
Person person = (Person) value;
writer.addAttribute("version", "0");
writer.startNode("fullname");
writer.setValue(person.getName());
writer.endNode();
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Person person = new Person();
reader.moveDown();
person.setName(reader.getValue());
reader.moveUp();
return person;
}
}
@Test
public void versioning() {
Person person = new Person();
person.setName("Davide");
XStream xStream = new XStream(new DomDriver());
xStream.registerConverter(new PersonConverter());
xStream.alias("person", Person.class);
System.out.println(xStream.toXML(person));
}
<person version="0">
<fullname>Davide</fullname>
</person>
a better solution is to decorate the default converter provided by XStream to add
versioning attribute to all domain objects without writing one Converter
class for each of them
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With