DataContractJsonSerializer Date Serialization

[亡魂溺海] 提交于 2019-12-07 10:41:02

问题


Is there a way to change how the DataContractJsonSerializer serializes dates?

Currently, it'll convert a date to something like:

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

I want to convert it into human readable date format.

I am building a RestApi using openrasta framework. Can i write OperationInterceptors which will at some stage before serialization/deserialization convert JSON datetime format to something which is human readable?Or is there any other way to do it?


回答1:


Use DataContractJsonSerializer constructor to pass your serialization settings:

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



回答2:


Finally i have handled this issue as 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 which we want to support which i have kept inside 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 clarifications.



来源:https://stackoverflow.com/questions/14640096/datacontractjsonserializer-date-serialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!