c# - JsonConvert.SerializeObject to class with non-nullable DateTime properties? -


background

i have json deserialized class has datetime properties.

sometimes corresponding elements of json null.

when try deserialize json class error thrown because plain old datetime can't accept null.

easy removes functionality

so easiest resolution make accepting properties of class nullable datetime (datetime?) if there's lot of datetime methods can no longer use on properties.

works ... weird ?

so in looking alternatives have considered following :

public class foorelaxed {     [required(errormessage = "please enter id.")]     public int? id { get; set; }      [required(errormessage = "please enter start date.")]     public datetime? startdate { get; set; }      [required(errormessage = "please enter 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 id.")]     public int id { get; set; }      [required(errormessage = "please enter start date.")]     public datetime startdate { get; set; }      [required(errormessage = "please enter 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 use these classes :

  • deserialize json class foorelaxed, has nullable datetime properties
  • validate properties of resulting object calling validator.tryvalidateobject on it.
  • assuming there no errors instantiate 'shadow' class, foostrict, has non-nullable datetime properties using foorexlaxed instance arg constructor
  • use foostrict subsequent processing

i'm sure there must better approach don't know . can suggest better solution ?

decorate appropriate jsonproperty attribute:

[jsonproperty(nullvaluehandling=nullvaluehandling.ignore)]

or

[jsonproperty("<nameofproperty>", nullvaluehandling=nullvaluehandling.ignore)]

final code be:

[jsonproperty("enddate", nullvaluehandling=nullvaluehandling.ignore)] public datetime enddate { get; set; }  [jsonproperty("startdate", nullvaluehandling=nullvaluehandling.ignore)] public datetime startdate { get; set; } 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -