我正在尝试使用MsgPack(Java)序列化对象。这个对象(除其他外)包含JodaTime的LocalDate用于表示 - well-date。 MsgPack无法反序列化我的消息,来自.NET客户端,因为它是非标准类型。我可以想出一种非常简单的方法来实现有效的行为 - 自定义序列化到一组整数左右。但是,由于缺少MsgPack的文档(这对于这么好的库来说是耻辱),我无法找到,如果有这样的选项(我希望它是......)。
有人可以给我指示一两个指针吗?
答案 0 :(得分:2)
使用开源,您可以查看并可能复制一些代码。在这种情况下,我建议你看看设计精良的MessagePack和复制模板。
使用MessagePack的Joda DateTime的自定义模板示例。以下模板将DateTime序列化为Long(Millis从1970年开始)并将其反序列化为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());