Serializing DataContractJsonSerializer

Is there a way to change how DateContractJsonSerializer serializes dates?

It is currently converting the date to something like:

{"date": "/ Date (1260597600000-0600) /"}

I want to convert it to a human readable format.

I am creating RestApi using the openrasta framework. Can I write OperationInterceptors, which at some stage before serializing / deserializing converts the JSON date and time format to something human-readable? Or is there any other way to do this?

+4
source share
2 answers

Finally, I examined this problem as shown below (C #)

[DataMember] public string Date { get; set; } [IgnoreDataMember] public DateTime? DateForInternalUse { get; set; } [OnSerializing] public void OnSerializing(StreamingContext context) { Date = (DateForInternalUse != null) ? ((DateTime)DateForInternalUse).ToString(DateTimeFormatForSerialization) : null; } [OnDeserialized] public void OnDeserialized(StreamingContext context) { try { DateForInternalUse = !String.IsNullOrEmpty(Date) ? DateTime.ParseExact(Date, DateTimeFormats, null, DateTimeStyles.None) : (DateTime?)null; } catch (FormatException) { DateForInternalUse = null; } } 

In this case, we can specify the formats that we want to support, which I saved in web.config

 <add key="DateTimePattern" value="yyyy-MM-dd,yyyy-MM-dd hh:mm:ss zzz,yyyy-MM-dd hh:mm:ss" /> 

Let me know for further clarification.

+1
source

Use the DataContractJsonSerializer constructor to pass serialization settings:

  var s = new DataContractJsonSerializer( typeof(YourTypeToSerialize), new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss") } ); 
+2
source

All Articles