DataContract and user set / get to set DateTime from string

I need to parse the JSON data from the server and make a list of objects.

I use DataContract to establish a connection between the fields of the json word and the properties of the class, however I have a problem: one of these fields contains a date in a string from (something like "2011-01-01 15:00 UTC"); I want to put this in a DateTime property.

How can I convert this string to datetime and pass it automatically using a DataContract? perhaps?

+4
source share
2 answers

You can use the property for this purpose:

[DataMember(Name="Foo")] public string FormattedFoo { get { return /* apply some custom formatting to 'Foo' */; } set { Foo = /* apply some custom parsing to 'value' */; } } public DateTime Foo {get;set;} 
+7
source

Put the DataMember in the field instead of the property and use setter / getter to convert:

 const string DATE_TIME_FORMAT = "<your format>"; [DataMember] string myDate; public DateTime MyDate { get { return DateTime.ParseExact(myDate, DATE_TIME_FORMAT, CultureInfo.CurrentCulture); } set { myDate = value.ToString(DATE_TIME_FORMAT); } } 
0
source

Source: https://habr.com/ru/post/1399014/


All Articles