【问题标题】:Rest Sharp DateTime deserializationRest Sharp DateTime 反序列化
【发布时间】:2015-11-02 17:46:37
【问题描述】:

我在使用 Rest Sharp 默认 json 反序列化时遇到以下问题

我有以下用户类

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?

【问题讨论】:

  • 在setter本身中做不是更容易吗?
  • 可以,但在用户类中这样做对我来说听起来并不干净

标签: c# .net json deserialization restsharp


【解决方案1】:

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 库,它是 RestSharp 的替代品,它在后台使用 Json.NET。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多