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 @xmlelementwrapper corresponds element want nest collection data withing.
  • each instance of firstjavaclass going correspond row element nested within firstclass element.

debugging trick

when jaxb object model not unmarshal correct, try:

  1. populating , marshalling xml.
  2. then compare xml trying unmarshal see differences are.
  3. adjusting annotations until marshalled xml matches trying unmarshal
  4. unmarshal xml.

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -