![](/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.