![](/img/trans.png)
[英]JsonConvert.SerializeObject() fails in serializing class with DateTime fields
[英]JsonConvert.SerializeObject to class with non-nullable DateTime properties?
背景
我有一些反序列化为具有DateTime
属性的类的JSON。
有时, JSON
的相应元素为null
。
当您尝试将JSON
反序列化为该类时,将引发错误,因为普通的旧DateTime
无法接受null
。
容易,但删除了功能
因此,最简单的解决方案是将类的接受属性设置为可为null的DateTime
( DateTime?
),但是如果这样做,那么将有很多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
结果对象的属性。 DateTime
属性。 我敢肯定,有比这更好的方法了,但我不知道它是什么。 谁能提出更好的解决方案?
用适当的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.