xml - JAXB - proper annotation of java class -
i have xml document such :
<parentclass> <firstclass> <row> <data1>...<data1> <data2>...<data2> </row> <row> <data1>...<data1> <data2>...<data2> </row> </firstclass> <secondclass> <row> <data1>...<data1> <data2>...<data2> </row> <row> <data1>...<data1> <data2>...<data2> </row> </secondclass> </parentclass> i have java classes below:
@xmlrootelement(name = "parentclass") @xmlaccessortype(xmlaccesstype.field) public class parentjavaclass { @xmlelement(name="firstclass") private list<firstjavaclass> fc; public list<firstjavaclass> getfc() { return fc; } public void setfc(list<firstjavaclass> fc) { this.fc = fc; } @xmlelement(name="secondclass") private list<secondjavaclass> sc; public list<secondjavaclass> getsc() { return sc; } public void setsc(list<secondjavaclass> sc) { this.sc = sc; } } @xmltype(name = "row", namespace = "fc") @xmlaccessortype(xmlaccesstype.field) public class firstjavaclass { private string data1; private string data2; // getters & setters } @xmltype(name = "row", namespace = "sc") @xmlaccessortype(xmlaccesstype.field) public class secondjavaclass { private string data1; private string data2; // getters & setters } but, when call
final parentjavaclass x = (parentjavaclass) jaxbunmarshaller.unmarshal(file); the resulting lists both firstjavaclass & secondjavaclass has null values. think "row" element tripping me, not sure how annotate correctly. please assist. thanks.
you should annotate follows:
@xmlelementwrapper(name="firstclass") @xmlelement(name="row") private list<firstjavaclass> fc; @xmlelementwrapper(name="secondclass") @xmlelement(name="row") private list<secondjavaclass> sc; the annotations mean:
- the
@xmlelementwrappercorresponds element want nest collection data withing. - each instance of
firstjavaclassgoing correspondrowelement nested withinfirstclasselement.
debugging trick
when jaxb object model not unmarshal correct, try:
- populating , marshalling xml.
- then compare xml trying unmarshal see differences are.
- adjusting annotations until marshalled xml matches trying unmarshal
- unmarshal xml.
Comments
Post a Comment