Is there a way to override how DataContractJsonSerializer serializes Dates?

烈酒焚心 提交于 2020-01-02 00:49:08

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7669144/is-there-a-way-to-override-how-datacontractjsonserializer-serializes-dates

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