The following example shows customizing XML serialization/deserialization process
using XmlAdapter.
We can specify the adapter to use by annotating the required property with
@XmlJavaTypeAdapter annotation.
public static void main (String [] args) throws JAXBException {
Foo foo = new Foo();
foo.setSecretNumber(new SecretNumber(1729));
/**
* Create JAXB Context from the classes to be serialized
*/
StringWriter output = new StringWriter();
JAXBContext context = JAXBContext.newInstance(Foo.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(foo, output);
System.out.println(output.toString());
/**
* Unmarshall
* Get the Foo object from XML string
*/
Unmarshaller um = context.createUnmarshaller();
StringReader sr = new StringReader(output.toString());
foo = (Foo) um.unmarshal(sr);
System.out.println("Secret Number : " + foo.getSecretNumber().getNumber());
}
}