I want marshal / unmarshal objects of a class that inherits another form.
I start with the class Thing:
import java.util.List;
public class Thing {
private List<String> strings;
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
}
I extend this class and annotate it with JAXB annotations.
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class JaxbThing extends Thing {
@XmlElementWrapper(name = "strings")
@XmlElement(name = "string")
public List<String> getStrings() {
return super.getStrings();
}
public void setStrings(List<String> string) {
super.setStrings(string);
}
}
Then I run the following marshalling / disassembling program:
import java.io.File;
import java.util.Arrays;
import javax.xml.bind.*;
public class Main {
public static void main(String[] args) {
JaxbThing t = new JaxbThing();
t.setStrings(Arrays.asList("a", "b", "c"));
try {
File f = new File("jaxb-file.xml");
JAXBContext context = JAXBContext.newInstance(JaxbThing.class);
Marshaller m = context.createMarshaller();
m.marshal(t, f);
Unmarshaller um = context.createUnmarshaller();
JaxbThing t2 = (JaxbThing) um.unmarshal(f);
System.out.println(t2.getStrings());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
XML file content:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxbThing>
<strings>
<string>a</string>
<string>b</string>
<string>c</string>
</strings>
</jaxbThing>
Everything seems right. But the unmarshaling result surprises me, because the console shows:
[
]
When I expected to see [a, b, c]
If I annotate a property stringsas follows:
@XmlElementWrapper(name = "list")
@XmlElement(name = "string")
public List<String> getStrings() {
return super.getStrings();
}
Then the console shows the expected [a, b, c].
I assume that JMXB unmarshaler uses the class Thinginstead JaxbThingto untie the contents of the XML file. In fact, if I annotate class Thingc @XmlTransient, I get the expected result.
JAXB.
- , ? .