tags:

views:

694

answers:

1

Hello,

I want to customize the marshalling of dates in JAXB. It's a variant of this already asked question. I would think I would use an XMLAdapter, as this answer questions specifies.

But I can't do that exactly, because I'm going the other way around, generating the JAXB beans from an .XSD -- I can't add annotations to the JAXB beans because they are generated code.

I've tried calling Marshaller.setAdapter(), but with 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's working
            }
            @Override
            public XMLGregorianCalendar unmarshal(String v) throws Exception {
              return null; // Don't care about this for now
            }
}

Where the relevant part of my generated JAXB bean looks like this:

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

When I do this, what the default date/XMLGregorianCalendar marshalling happens. It's as if I didn't do it all.

Any help is appreciated.

Thanks,

Charles

A: 

The preferred way to change the bound type on the XJC-generated Java is to use a binding customization.

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

JAXB has a built-in table that determines what Java classes are used to represent what XML Schema built-in types, but this can be customized.

One of the common use cases for customization is to replace the XMLGregorianCalendar with the friendlier Calendar or Date. XMLGregorianCalendar is designed to be 100% compatible with XML Schema's date/time system, such as providing infinite precision in sub-seconds and years, but often the ease of use of those familiar Java classes win over the precise compatibility.

That page doesn't tell you how to actually wire up the customization, though, so have a look here to see how to do that:

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

skaffman
Thanks, that works. I was new to JAXB and didn't realize you could customize the bindings like that.
Charles O.