0

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?

Jake B
  • 672
  • 1
  • 9
  • 21
  • What XML representation are you trying to achieve? Are you trying to determine the subclass strictly by which elements are present? – bdoughan Feb 06 '14 at 21:22
  • Basically I wanted to marshal either phone number or address into a root and have them be able to unmarshaled to their proper subclass without having to be wrapped into a list as in your example. After reading this other question, You said "@XmlJavaTypeAdapter only applies to fields/properties referencing that class, and not when an instance of that class is a root object in your XML tree." This makes me think I should make another class AdapterContactMethod much like you have in the XmlAdapter annotate it with XmlRootElement and handle the subclass conversion myself. – Jake B Feb 06 '14 at 21:37

1 Answers1

0

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.

Jake B
  • 672
  • 1
  • 9
  • 21