Search code examples
javaserializationxml-serializationxstream

XStream: Deserialisation of a serialised java.sql.Time causes error


The following code throws an exception, which I didn't expect at all!

        long now = System.currentTimeMillis();
        java.sql.Time t1 = new java.sql.Time(now);
        String s1 = new XStream().toXML(t1);
        java.sql.Time t2 = (java.sql.Time) new XStream().fromXML(s1);
        if(!t1.equals(t2)) throw new IllegalArgumentException();

See XStream

The question is, why, and is it a bug in XStream?


Solution

  • A quick Google search gives that XStream uses this class to serialize java.sql.Time: http://x-stream.github.io/javadoc/com/thoughtworks/xstream/converters/extended/SqlTimeConverter.html

    Note the warning:

    Converts a java.sql.Time to text. Warning: Any granularity smaller than seconds is lost.

    So it's being truncated to an even second, and thus the comparison with the original (which has milliseconds) fails.