繁体   English   中英

JsonConvert.SerializeObject使用非空DateTime属性进行分类?

[英]JsonConvert.SerializeObject to class with non-nullable DateTime properties?

背景

我有一些反序列化为具有DateTime属性的类的JSON。

有时, JSON的相应元素为null

当您尝试将JSON反序列化为该类时,将引发错误,因为普通的旧DateTime无法接受null

容易,但删除了功能

因此,最简单的解决方案是将类的接受属性设置为可为null的DateTimeDateTime? ),但是如果这样做,那么将有很多DateTime方法无法在这些属性上使用。

可以,但是...很奇怪?

因此,在寻找替代方案时,我考虑了以下几点:

public class FooRelaxed
{
    [Required(ErrorMessage = "Please enter the id.")]
    public int? Id { get; set; }

    [Required(ErrorMessage = "Please enter the Start Date.")]
    public DateTime? StartDate { get; set; }

    [Required(ErrorMessage = "Please enter the End Date.")]
    public DateTime? EndDate { get; set; }

    public FooRelaxed() { }

    public FooRelaxed(
                  int? id,
                  DateTime? startdate,
                  DateTime? enddate)
    {
        this.Id = id;
        this.EndDate = enddate;
        this.StartDate = startdate;
    }
}
public class FooStrict 

    [Required(ErrorMessage = "Please enter the id.")]
    public int Id { get; set; }

    [Required(ErrorMessage = "Please enter the Start Date.")]
    public DateTime StartDate { get; set; }

    [Required(ErrorMessage = "Please enter the End Date.")]
    public DateTime EndDate { get; set; }

    public FooStrict() { }

    public FooStrict(FooRelaxed obj)
    {
        this.Id = Convert.ToInt32(obj.Id);
        this.EndDate = Convert.ToDateTime(obj.EndDate);
        this.StartDate = Convert.ToDateTime(obj.StartDate);
    }
}

然后,我将这些类用于:

  • JSON反序列化为FooRelaxed类,该类具有可空的DateTime属性
  • 通过在对象上调用Validator.TryValidateObject结果对象的属性。
  • 假设没有错误,然后使用FooRexlaxed实例作为构造函数的arg实例化“ shadow”类FooStrict,该类具有不可空的DateTime属性。
  • 使用FooStrict进行所有后续处理

我敢肯定,有比这更好的方法了,但我不知道它是什么。 谁能提出更好的解决方案?

用适当的JsonProperty属性进行装饰:

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]

要么

[JsonProperty("<NameOfProperty>", NullValueHandling=NullValueHandling.Ignore)]

最终代码为:

[JsonProperty("EndDate", NullValueHandling=NullValueHandling.Ignore)]
public DateTime EndDate { get; set; }

[JsonProperty("StartDate", NullValueHandling=NullValueHandling.Ignore)]
public DateTime StartDate { get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM