WCF Client how can I deserialize an incompatible date format from the JSON response?

喜夏-厌秋 提交于 2019-12-05 05:29:43

Two things I can think of:

  1. Change LastModified to be a string and then convert it to a Datetime object yourself. It would mean exposing two properties for the same data on your object though.
  2. Write a IDispatchMessageInspector to intercept the message before the deserialization occurs and massage the raw message using regex. It would allow a one stop solution for all dates in your service.

So far this is the best I have come up with:

I have an internal string Extension method:

internal static class DeserializationHelper
{
    internal static DateTime GetDeserializedDateTime(this string @string)
    {
        if (string.IsNullOrEmpty(@string)) return default(DateTime);
        //insert complex custom deserialization logic here
        return DateTime.Parse(@string);
    }

}

This is the DataMember setup:

[DataMember(Name = "lastmodified")]
internal string _LastModified 
{
    set { LastModified = value.GetDeserializedDateTime(); }
    //getter is not needed for receiving data but WCF requires one
    get { return default(string); }
}

public DateTime LastModified { get; private set; }

If you wanted to use this DataContract for sending data (make this a writeable Property), you would have to write a DateTime Extension method (GetSerializedDateString), expand the setters/getters and introduce private members as go-betweens.

It smells of cut and paste, and it does not take advantage of any WCF framework features. What would Bill Gates do?

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