2

我正在尝试使用 MsgPack (Java) 序列化对象。这个对象(除其他外)包含 JodaTime 的 LocalDate 用于表示 - 以及 - 日期。MsgPack 无法反序列化来自 .NET 客户端对应的消息,因为它是非标准类型。我可以想到一种非常简单的方法来实现有效行为 - 自定义序列化为一组整数左右。但是,由于缺少 MsgPack 的文档(对于这么好的库来说这是一种耻辱),我无法找到,是否有这样的选项(我希望它是,...)。

有人可以给我一两个关于在哪里看的指针吗?

4

1 回答 1

2

使用开源,您可以查看并可能复制一些代码片段。在这种情况下,我建议您查看精心设计的 MessagePack 并复制模板。

使用 MessagePack 的 Joda DateTime 自定义模板示例。以下模板将 DateTime 序列化为 Long(1970 年的 Millis)并将其反序列化回 UTC(DateTimeZone.UTC)。如果您希望保持正确的时区,可以轻松扩展:

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();

}

在您的班级中只需注册上面的模板:

msgpack = new MessagePack();
msgpack.register(DateTime.class, DateTimeSerializerTemplate.getInstance());
于 2013-12-01T20:01:17.403 回答