JaxB inheritance marshalling abstract classes

时光毁灭记忆、已成空白 提交于 2020-01-06 15:20:08

问题


I've been searching for the best way to perform the following action using JaxB but I cannot find a way that works. I followed the tutorial here to allow for marshaling and unmarshaling of subclasses.

It achieves all that I am looking for, except that in order for the subclasses to be properly marshaled and unmarshaled, they must be wrapped in a class with a specific @XmlRootElement. This doesn't allow you to represent the classes themselves as Xml on their own.

I want to have a classes like so:

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;   

@XmlJavaTypeAdapter(ContactMethodAdapter.class) 
public abstract class ContactMethod {   

}

public class Address extends ContactMethod {       

    protected String street;      
    protected String city;   

}

public class PhoneNumber extends ContactMethod {       

    protected String number;   

}

and I want to be able to perform the following:

Input:

<contact-method>
   <street>Broadway</street>
   <city>Seattle</city>
</contact-method>

Main:

public class Demo {       
   public static void main(String[] args) throws Exception  {         
      ContactMethod meth = (ContactMethod ) unmarshaller.unmarshal(xml);

      if(ContactMethod instanceof Address){
         Address addr = (Address) meth;

         addr.getStreet();

         // etc.
      }

      Address marshalAddr = new Address("Broadway", "Seattle");       

      Marshaller marshaller = jc.createMarshaller();         
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);         
      marshaller.marshal((ContactMethod) marshalAddr, System.out);     
   }   
}

Output:

<contact-method>
   <street>Broadway</street>
   <city>Seattle</city>
</contact-method>

does anyone know how this can be accomplished?


回答1:


I ended up using one class (AdaptedContactMethod) to model the abstract class. Then I handled the marshaling and unmarshalling to the different subclasses on my own rather than through an @XmlJavaTypeAdapter.

This allows you to put @XmlRootElement on your AdaptedContactMethod implementation without having to wrap it in a list.



来源:https://stackoverflow.com/questions/21612210/jaxb-inheritance-marshalling-abstract-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!