سؤال

My hierarchy of classes:

@XmlAccessorType(XmlAccessType.FIELD)
public abstract class GenericItem  {
    @XmlElement(name = "Id", required = true)
    private String itemId;
    ////other fields
} 

@XmlAccessorType(XmlAccessType.FIELD)
public class Item extends GenericItem {
   @XmlElement(name = "AreaType", required = true)
   private String areaType;
   ///other fields
}


@XmlAccessorType(XmlAccessType.FIELD)
public abstract class GenericData<T extends GenericItem>{

  @XmlElement(name = "Item")
  private List<T> itemList;

  public List<T> getItemList() {
    return itemList;
  }

  public void setItemList(List<T> itemList) {
    this.itemList = itemList;
  }
  ////other fields
}


 @XmlRootElement(name = "Data")
 @XmlAccessorType(XmlAccessType.FIELD)
 public class Data extends GenericData<Item> {
   ////other fields
 }  

When I try to unmarahal XML-document that looks like

 <Data>
   <Item/>
   <Item/>
 </Date>

I have error javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.SAXParseException2;Unable to create an instance of GenericItem]

  JAXBContext jc = JAXBContext.newInstance(Data.class, GenericData.class,Item.class, GenericItem.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        --error here--> JAXBElement<Data> jb = unmarshaller.unmarshal(xmlStreamReader, Data.class);

Please, I need help :(

هل كانت مفيدة؟

المحلول

As a work around, remove the abstract key word and try for the generic classes.

list of java classes to be recognized by the new JAXBContext. 

This is what documentation says for classesToBeBound parameters, which says it should be able to create a new object to recognize the parameters. In case of abstract class, it is not possible.

Try with a combination of @MappedSuperclass and @XmlSeeAlso. Annotate the base classes with those and make them abstract.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top