How to configure JAXB Marshalling when generating JAXB beans from XML

I want to set up date sorting in JAXB. This is a variant of this already asked question . I would think that I would use the XMLAdapter as indicated by this answer .

But I canโ€™t do it exactly, because I go the other way, generating JAXB beans from .XSD - I canโ€™t add annotations to JAXB beans because they are generated code.

I tried calling Marshaller.setAdapter () but no luck.

final Marshaller marshaller = getJaxbContext().createMarshaller(); marshaller.setSchema(kniSchema); marshaller.setAdapter(new DateAdapter()); ... private static class DateAdapter extends XmlAdapter<String, XMLGregorianCalendar> { @Override public String marshal(XMLGregorianCalendar v) throws Exception { return "hello"; //Just a test to see if it working } @Override public XMLGregorianCalendar unmarshal(String v) throws Exception { return null; // Don't care about this for now } } 

If the relevant part of my generated JAXB bean is as follows:

  @XmlSchemaType(name = "date") protected XMLGregorianCalendar activeSince; 

When I do this, what happens by default is date / XMLGregorianCalendar marshalling. As if I didnโ€™t do it.

Any help is appreciated.

Thanks,

Charles

+6
jaxb
source share
1 answer

The preferred way to change the bound type in Java created by XJC is to use a binding setting.

https://jaxb.dev.java.net/guide/Using_different_datatypes.html

JAXB has an inline table that determines which Java classes are used to represent the inline inline XML schema types, but this can be customized.

One common use case for customization is to replace XMLGregorianCalendar with a friendly calendar or date. The XMLGregorianCalendar is designed to be 100% compatible with the XML date / time schema, for example, providing infinite precision in sub sessions and years, but often the ease of use those familiar Java classes defeat exact compatibility.

This page does not tell you how to actually configure the setting, so look here to find out how to do it:

http://jaxb.java.net/tutorial/section_5_6_1-Overriding-the-Datatype.html#Overriding%20the%20Datatype

+2
source share

All Articles