user994121 user994121 - 3 months ago 20
Java Question

XStream fromXML for moved property

Given a class Parent, which has been serialized to XML.

class Parent {
Object A;
Child child;
}

class Child {
Object C;
...
}


If the property C is moved from the Child object to the parent, as follows

class Parent {
Object A;
Object C;
Child child;
}

class Child {
...
}


For XML files made before the change, how do you make sure the child c tag populates the new property in the parent when deserializing with xstream?

Answer

Since you are deserializing the xml, it was already generated, and a serialVersionUID was generated (it means if there is any difference in the class which was compiled again, another serialVersionUID will be generated), so it doesn't have this attribute defined on it, when you deserialize it and try to cast, it is going to throw an exception.

You will have to deserialize the two classes (Parent and Child) and set it on code like:

XStream xstream = new XStream();

NewParent newParent = new NewParent();
OldParentWithoutC oldParent = (OldParentWithoutC) xstream.fromXML(xml);
OldChild oldChild = (OldChild) xstream.fromXML(xml);

newParent.setObjectC(oldChild.getC());
String xml = xstream.toXML(newParent);

Then you can serialize it again.

Comments