XML : JAXB Inheritance + XMLAdapter (HasMap)

I am making an app, that will contain data in XML file.

I stuck right now with one problem: JAXB do not marshall my child class, so when I umarshall XML file, all objects are objects of Parent class. I tried some variations with @XMLSeeAlso, AccessType.FIELD and JAXBContext jaxbContext = JAXBContext.newInstance(Important.class, Parent.class, Child.class); , but it seems like I missunderstand something, and it doesn't work.

Could you give me some advices? What annotations should I use? or mb XMLAdapter? The current structure of my project is (I tried to simplify it):

Main.java

  public class Main {      public static void main(String args[]){          JAXB jaxb = new JAXB();          Parent parent = new Parent(1);          Child child = new Child(2,3)          Important important = new Important();          jaxb.write(important);      }   }    

Important.java

  @XmlRootElement(name="important")  public class Important {  public Map<Integer, Parent> hashMap;      //some code here  }    

Parent.java

  public class Parent{      public int parentField;      //constructor  }    

Child.java

  public class Child extends Parent {      public int childField;      //constructors  }    

And simple JAXB class. JAXB.java

  public class JAXB {      public void write(Important important) {          try {              JAXBContext jaxbContext = JAXBContext.newInstance(Important.class);              Marshaller jaxbMarshaller = jaxbContext.createMarshaller();              jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);              jaxbMarshaller.marshal(important, System.out);            } catch (JAXBException e) {              System.err.println(e + "Error.");          }      }  }    

But after marshalling it returns XML, that doesn't contain any information about child.

  <important>     <hashMap>         <entry>             <key>0</key>             <value>                 <parentField>1</parentField>             </value>         </entry>         <entry>             <key>0</key>             <value>                 <parentField>2</parentField>             </value>         </entry>     </hashMap>    

and then closing tag.

My map 100% contains different types of classes: Parent and Child

Any thoughts?

No comments:

Post a Comment