如何在没有\ / Date的情况下格式化JSON日期?

时间:2013-02-15 05:22:10

标签: c# serialization

我需要这种格式的格式JSON日期:docDate“:”1360905419116“,”,“inDocDate”:“1360905419116”,等等。

我的序列号:

JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string result = jsonSerializer.Serialize( new {
    docDate = DateTime.Now,
    inDocDate = DateTime.Now,
    outDocDate = DateTime.Now } );

序列化后收到的结果:

{"docDate":"\/Date(1360905419116)\/","inDocDate":"\/Date(1360905419116)\/","outDocDate":"\/Date(1360905419116)\/"}

我想要

{"docDate":"1360905419116","inDocDate":"1360905419116","outDocDate":"1360905419116"}

1 个答案:

答案 0 :(得分:0)

您可以使用此扩展方法

public static class DateTimeExtensions
{
  internal static readonly long DatetimeMinTimeTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;

  public static long ToJsTime(this DateTime dateTime)
  {
    return (dateTime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000L;
  }
}

所以你的代码变成了:

string result = jsonSerializer.Serialize( new {
    docDate = DateTime.Now.ToJsTime().ToString(),
    inDocDate = DateTime.Now.ToJsTime().ToString(),
    outDocDate = DateTime.Now.ToJsTime().ToString() } );