簡體   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