2015-11-02 91 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的替代品。