Why can DateTime.MinValue not be serialized in timezones ahead of UTC?

后端 未结 7 1002
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 02:09

I am experiencing issues with a WCF REST service. The wire object that I try to return has certain properties not set, resulting in DateTime.MinValue for properties of type

7条回答
  •  暖寄归人
    2020-12-24 02:21

    I believe a more elegant way is to instruct the serializer not to emit the default value for DateTime fields. This will save some byte during transfer and some processing when serializing for the fields that you don't have any value for them. Example:

    [DataContract]
    public class Document {
        [DataMember] 
        public string Title { get; set; }
        [DataMember(IsRequired = false, EmitDefaultValue = false)] 
        public DateTime Modified { get; set; } 
    }
    

    or you can use Nullables. Example:

    [DataContract]
    public class Document {
        [DataMember] 
        public string Title { get; set; }
        [DataMember] 
        public DateTime? Modified { get; set; } 
    }
    

    It all depends on the requirements and restrictions you might have in your project. Sometimes you cannot just change the data types. In that case you can still take advantage of DataMember attribute and keep the data types intact.

    In the above example if you have new Document() { Title = "Test Document" } in the server side, when serialized to JSON it will give you {"Title": "Test Document"} so it will be easier to deal with in JavaScript or any other client in the other side of the wire. In JavaScript if you JSON.Parse() it, and try to read it, you will get back undefined. In typed languages you will have the default value for that property depending on the type (which is typically the expected behavior).

    library.GetDocument(id).success(function(raw){ 
        var document = JSON.Parse(raw);
        var date = document.date; // date will be *undefined*
        ...
    }
    

提交回复
热议问题