Search code examples
javajodatimexstream

Xstream's jodatime Local Date display


I'm using xstrem to serialise a jodatime local date into xml. However when output the generated xml the LocalDate is not in an easily readable format. See below:

<date>
    <iLocalMillis>1316563200000</iLocalMillis>
    <iChronology class="org.joda.time.chrono.ISOChronology" reference="../../tradeDate/iChronology"/>

Any ideas how I can get xstream to display the date in a format that won't drive me up the wall?


Solution

  • Here's what I have used successfully. I believe I used the info at the link mentioned in the first post.

    import java.lang.reflect.Constructor;
    
    import org.joda.time.DateTime;
    
    import com.thoughtworks.xstream.converters.Converter;
    import com.thoughtworks.xstream.converters.MarshallingContext;
    import com.thoughtworks.xstream.converters.UnmarshallingContext;
    import com.thoughtworks.xstream.io.HierarchicalStreamReader;
    import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
    
    
    public final class JodaTimeConverter implements Converter {
    
        @Override
        @SuppressWarnings("unchecked")
        public boolean canConvert(final Class type) {
                return (type != null) && DateTime.class.getPackage().equals(type.getPackage());
        }
    
        @Override
        public void marshal(final Object source, final HierarchicalStreamWriter writer,
                final MarshallingContext context) {
                writer.setValue(source.toString());
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public Object unmarshal(final HierarchicalStreamReader reader,
                final UnmarshallingContext context) {
                try {
                        final Class requiredType = context.getRequiredType();
                        final Constructor constructor = requiredType.getConstructor(Object.class);
                        return constructor.newInstance(reader.getValue());
                } catch (final Exception e) {
                    throw new RuntimeException(String.format(
                     "Exception while deserializing a Joda Time object: %s", context.getRequiredType().getSimpleName()), e);
                }
        }
    
    }
    

    You can register it like:

    XStream xstream = new XStream(new StaxDriver());
    xstream.registerConverter(new JodaTimeConverter());