2015-11-02 47 views
0

我在使用REST夏普默认JSON序列化休息夏普的DateTime反序列化

下面的问题我有以下的用户类

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", 
    } 
] 

默认休息Sharp将此日期序列化为DateTime最小值{01/01/0001 00:00:00},但如何覆盖此行为并在此情况下为空?

+0

在setter本身做它不是更容易吗? – dbc

+0

这将是,但它不听起来干净,我在User类中做到这一点 – Piotr

回答

0

看来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); 

这基本上是说,两个非空的和可空日期属性,解析到非可空类型。

因此,您的选择是自定义反序列化行为(信息here),或使用确实支持可空日期的事件(如Json.NET)进行反序列化。另一种选择是使用我的Flurl库,它是使用JSON.NET的RestSharp的替代品。