Question

I'm trying to serialize object with MsgPack (Java). This object (among other things) contains JodaTime's LocalDate for representing - well - date. MsgPack is not able to deserialize my message, coming from .NET client counterpart, because it is non-standard type. I can think of a VERY SIMPLE way to achieve the valid behavior - custom serialization to a set of integers or so. But, due to lack of a documentation for MsgPack (which is shame for such a nice library), I'm not able to find, if there is such option or not (I hope it is,...).

Can someone give me a pointer or two on where to look, please?

Was it helpful?

Solution

With Open Source you get ability to to review and possibly copy some bits and pieces of code. In this case I suggest you look at well designed MessagePack and copy Templates.

Example of custom Template for Joda DateTime using MessagePack. Following Template serializes DateTime to Long (Millis from 1970) and deserializes it back in UTC (DateTimeZone.UTC). If you wish to maintain correct time zone it may be easily extended:

public class DateTimeSerializerTemplate extends AbstractTemplate<DateTime> {
    private DateTimeSerializerTemplate() {

    }

    public void write(Packer pk, DateTime target, boolean required) throws IOException {
        if (target == null) {
            if (required) {
                throw new MessageTypeException("Attempted to write null");
            }
            pk.writeNil();
            return;
        }
        pk.write(target.getMillis());
    }

    public DateTime read(Unpacker u, DateTime to, boolean required) throws IOException {
        if (!required && u.trySkipNil()) {
            return null;
        }
        return new DateTime(u.readLong(), DateTimeZone.UTC);
    }

    static public DateTimeSerializerTemplate getInstance() {
        return instance;
    }

    static final DateTimeSerializerTemplate instance = new DateTimeSerializerTemplate();

}

In your Class just register the template above:

msgpack = new MessagePack();
msgpack.register(DateTime.class, DateTimeSerializerTemplate.getInstance());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top