我在使用Rest Sharp默认json反序列化时遇到了以下问题
我有以下User类
public partial class User
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime? Date { get; set; }
}
和下面的json消息:
[
{ "id":1,
"name":"Adam",
"date":"0000-00-00 00:00:00",
}
]
默认情况下,Rest Sharp将此日期序列化为DateTime最小值{01/01/0001 00:00:00},但是在这种情况下,我如何覆盖此行为并获得null?
发布于 2015-11-04 16:14:59
看起来RestSharp's JSON serializer并没有像您期望的那样处理可以为空的日期。相关代码如下:
if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))
return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
这基本上是说,对于不可空和可空的date属性,都要解析为不可空的类型。
因此,您的选择是定制反序列化行为(信息here),或者使用支持可空日期的内容(如Json.NET )反序列化响应。另一种选择是使用我的Flurl库,这是RestSharp的一个替代方案,它在幕后使用Json.NET。
https://stackoverflow.com/questions/33483718
复制