protobuf-net无法反序列化DateTime.Kind正确 [英] protobuf-net does not deserialize DateTime.Kind correctly

查看:80
本文介绍了protobuf-net无法反序列化DateTime.Kind正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用protobuf-net.dll 1.0.0.280版

using protobuf-net.dll Version 1.0.0.280

当我反序列化DateTime(包装在对象中)时,日期/时间还可以,但是DateTime.Kind属性为未指定"

When I deserialize a DateTime (wrapped in an object), the date/time is ok but the DateTime.Kind property is 'Unspecified'

考虑此测试用例以对DateTime进行序列化/反序列化.

Consider this test case to serialize/deserialize a DateTime.

[TestMethod]
public void TestDateTimeSerialization()
{
    var obj = new DateTimeWrapper {Date = DateTime.UtcNow};
    obj.Date = DateTime.SpecifyKind(obj.Date, DateTimeKind.Utc);
    var serialized = obj.SerializeProto();
    var deserialized = serialized.DeserializeProto<DateTimeWrapper>();
    Assert.AreEqual(DateTimeKind.Utc, deserialized.Date.Kind);
}

public static byte[] SerializeProto<T>(this T item) where T : class
{
    using (var ms = new MemoryStream())
    {
        Serializer.Serialize(ms, item);
        return ms.ToArray();
    }
}

public static T DeserializeProto<T>(this byte[] raw) where T : class, new()
{
    using (var ms = new MemoryStream(raw))
    {
        return Serializer.Deserialize<T>(ms);
    }
}

断言失败,种类== Unspecified

The Assert fails, the Kind == Unspecified

由于protobuf-net不序列化此属性(请参见下文),一种解决方案是在客户端显示日期时假定DateTimeKind等于Utc(仅当您知道时)当然应该是UTC):

As a result of protobuf-net not serializing this property (see below) one solution is to assume DateTimeKind is equal to Utc when displaying dates on the client side (only where you know it should be UTC of course):

public static DateTime ToDisplayTime(this DateTime utcDateTime, TimeZoneInfo timezone)
{
    if (utcDateTime.Kind != DateTimeKind.Utc)//may be Unspecified due to serialization
        utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
    DateTime result = TimeZoneInfo.ConvertTime(utcDateTime, timezone);
    return result;
}

这省去了在接收端分配每个DateTime属性的麻烦.

This saves you having to assign to each DateTime property on the receiving side.

推荐答案

protobuf.net必须保持与protobuf二进制格式的兼容性,该格式是为Java日期/时间数据类型设计的. Java中没有Kind字段->没有protobuf二进制格式的Kind支持-> Kind未通过网络传输.或类似的东西.

protobuf.net has to maintain compatibility with the protobuf binary format, which is designed for the Java date/time datatypes. No Kind field in Java -> No Kind support in the protobuf binary format -> Kind not transferred across the network. Or something along those lines.

事实证明,protobuf.net对Ticks字段进行了编码(仅),您可以在

As it turns out, protobuf.net encodes the Ticks field (only), you'll find the code in BclHelpers.cs.

但是请随时在protobuf消息定义中为此值添加另一个字段.

But feel free to add another field in your protobuf message definition for this value.

这篇关于protobuf-net无法反序列化DateTime.Kind正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆