Is there a way to override how DataContractJsonSerializer serializes Dates?
Asked Answered
B

4

14

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 would rather have it serialize as just the milliseconds since utc 1970. That way, other languages can easily work with the json data.

Brentwood answered 6/10, 2011 at 0:8 Comment(0)
M
9

No, there's no hook in the serializer itself to do that. But you can use some of the serialization callbacks to implement this same behavior. You'd create another data member (of type string), and before the data is serialized, an [OnSerializing] callback would be invoked to copy the value of the DateTime field to the string one. The section "Fine-grained control of serialization format for primitives" in the post about serialization surrogates (at http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx) shows more details of what needs to be done.

Megaton answered 7/10, 2011 at 2:6 Comment(0)
S
1

Well there is a workaround described here http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx under the topic "Fine-grained control of serialization format for primitives".

The main idea is to use a string backing field for the unserialized values and a property which performs serialzation and deserialzation in the setter and getter. That´s not ideal from the performance view but it could be a solution in some situations.

Solenoid answered 30/9, 2013 at 8:21 Comment(0)
S
0

Perhaps the DataContractJsonSerializerSettings.DateTimeFormat may be helpful

Senescent answered 26/7, 2020 at 10:55 Comment(0)
I
0
        DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings
        {
            DateTimeFormat = new DateTimeFormat("yyyy-MM-dd HH:mm:ss")
        };
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
Ingleside answered 19/4 at 11:3 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Yungyunick

© 2022 - 2024 — McMap. All rights reserved.