序列化.NET日期时间为JSON字符串 [英] Serializing .NET DateTime to Json string
问题描述
我正在写一个自定义的JSON序列化,以提高我的服务的PERF。是的,我也认为Json.NET,servicestack,DataContractJsonSerializer等之前,我做了决定。我的目标是持平,简单的.NET类型和我想避免的一个更大的图书馆的开销。
I'm writing a custom Json serializer to improve the perf of my service. And yes, I did consider Json.NET, servicestack, DataContractJsonSerializer, etc before I made the decision. My objects are flat with simple .NET types and I wanted to avoid the overhead of a much bigger library.
不管怎么说,这里是我遇到一个小问题。我有code序列化的DateTime -
Anyways, here is where I run into a small problem. I have the code to serialize DateTime -
var epoch = new DateTime(1970, 1, 1, 0, 0, 0);
sb.Append("\"\\/Date(");
SerializeNumber((time - epoch).TotalMilliseconds, sb);
sb.Append(")\\/\"");
和这个伟大的工程,但我不能完全得到它相匹配的默认.NET JSON序列输出。
And this works great, except I can't quite get it to match the default .NET Json serializer in the output.
.NET serializer
"\\/Date(1328057884253)\\/\"
Custom serializer
"\\/Date(1328057884253.04)\\/\"
嗯,所以我试图让我的转换少precise并切换到的(INT)TotalSeconds而不是毫秒,这给了我这一点 -
Hmm, so I tried making my conversion less precise and switching to (int)TotalSeconds instead of milliseconds and that gives me this -
.NET serializer
"\\/Date(1328054810067)\\/\"
Custom serializer
"\\/Date(1328054810)\\/\"
我猜,这不会是一个大问题,但它会很高兴让我通过对默认的.NET序列化只是理智的单元测试。任何想法?
I'm guessing that this wouldn't be a big deal but it would be nice to get my unit tests passing against the default .NET serializer just for sanity. Any ideas?
感谢。
推荐答案
该物业的 TotalMilliseconds 的类型是双。你可以只投它变成一个长而不是使用TotalSeconds方法,它当然不会返回相同的值...
The Property TotalMilliseconds is of type double. You could just cast it into a long instead of using the TotalSeconds method which of course doesn't return the same value...
var epoch = new DateTime(1970, 1, 1, 0, 0, 0);
sb.Append("\"\\/Date(");
SerializeNumber((long)(time - epoch).TotalMilliseconds, sb);
sb.Append(")\\/\"");
修改的:作为信贷基金在评论中说,preFER 长为 INT ,以避免产能溢出。
edit: as Kosh said in comments, prefer long to int to avoid capacity overflow.
这篇关于序列化.NET日期时间为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!