我正在尝试使用 MsgPack (Java) 序列化对象。该对象(除其他外)包含 JodaTime 的 LocalDate,用于表示日期。 MsgPack 无法反序列化来自 .NET 客户端对应项的消息,因为它是非标准类型。我可以想到一种非常简单的方法来实现有效的行为 - 自定义序列化为一组整数左右。但是,由于缺少 MsgPack 的文档(对于这么好的库来说这是耻辱),我无法找到是否有这样的选项(我希望有,...)。
有人可以给我一两点建议吗?
最佳答案
通过开源,您可以查看并可能复制一些代码片段。在这种情况下,我建议您查看设计良好的 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();
}
在您的类(class)中只需注册上面的模板即可:
msgpack = new MessagePack();
msgpack.register(DateTime.class, DateTimeSerializerTemplate.getInstance());
关于java - MsgPack第三方对象序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14763463/