[英]JsonConvert.SerializeObject to class with non-nullable DateTime properties?
Background 背景
I have some JSON which is deserialized to a Class which has DateTime
properties. 我有一些反序列化为具有DateTime
属性的类的JSON。
Sometimes the corresponding elements of the JSON
are null
. 有时, JSON
的相应元素为null
。
When you try to deserialize the JSON
to the class an error is thrown because a plain old DateTime
can't accept a null
. 当您尝试将JSON
反序列化为该类时,将引发错误,因为普通的旧DateTime
无法接受null
。
Easy but removes functionality 容易,但删除了功能
So the easiest resolution is to make the accepting properties of the class a nullable DateTime
( DateTime?
) but if you do that there's then a lot of DateTime
methods you can no longer use on those properties. 因此,最简单的解决方案是将类的接受属性设置为可为null的DateTime
( DateTime?
),但是如果这样做,那么将有很多DateTime
方法无法在这些属性上使用。
Works but ... weird ? 可以,但是...很奇怪?
So in looking for alternatives I have considered the following : 因此,在寻找替代方案时,我考虑了以下几点:
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);
}
}
I then use these classes to : 然后,我将这些类用于:
JSON
to the class FooRelaxed, which has nullable DateTime
properties 将JSON
反序列化为FooRelaxed类,该类具有可空的DateTime
属性 Validator.TryValidateObject
on it. 通过在对象上调用Validator.TryValidateObject
结果对象的属性。 DateTime
properties using the FooRexlaxed instance as an arg to the constructor 假设没有错误,然后使用FooRexlaxed实例作为构造函数的arg实例化“ shadow”类FooStrict,该类具有不可空的DateTime
属性。 I'm sure there must be a better approach than this but I don't know what it is . 我敢肯定,有比这更好的方法了,但我不知道它是什么。 Can anyone suggest a better solution ? 谁能提出更好的解决方案?
Decorate with appropriate JsonProperty
attribute: 用适当的JsonProperty
属性进行装饰:
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
Or 要么
[JsonProperty("<NameOfProperty>", NullValueHandling=NullValueHandling.Ignore)]
Final code would be: 最终代码为:
[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.