Re: [Simple-support] Deserilize objects with inheritance
Brought to you by:
niallg
|
From: Simon B. <sim...@if...> - 2012-08-07 04:42:52
|
You need to remove the @Root annotation from class B.Nhat Ngo <phu...@gm...> hat geschrieben:Hi everyone,
I'm a student, new to SimpleXML library. Per the title suggested, I am having a huge problem deserializing a stored inherited object using Java SimpleXML library. Let's say my codes are:
@Root(name="a")
public class A {
@Attribute(name="id")
protected int id;
public A(@Attribute(name="id") int id){
this.id = id;
}
}
@Root(name="b")
public class B extends A {
@Element(name="key",type=int.class)
private int key;
public B(int id,
@Element(name="key",type=int.class) int key) {
super(id);
this.key = key;
}
}
public class Main {
public static void Main() {
File src = new File("example.xml");
Serializer serializer = new Persister();
//Serialize the object
B b = new B(1,1);
serializer.write(b, src);
//Error here, deserialize the object
B b2 = serializer.read(B.class, src);
}
}
There is no error and the Serializer happily serializes the object b to:
<b id="1">
<key>1</key>
</b>
Now when I attempt to deserialize it, the program throws:
org.simpleframework.xml.core.PersistenceException: Constructor not matched for class B
How should I annotate both class A and B to behave correctly? I've tried put in @Attribute(name="id") in B constructor to no avail and the serializer failed to serialize anything.
Thanks.
|