【问题标题】:Controlling serialization format of a KeyValuePair<DateTime, long>'s key控制 KeyValuePair<DateTime, long> 的键的序列化格式
【发布时间】:2013-02-23 03:37:28
【问题描述】:

我正在尝试获取与 .NET 4.5 中的 WebAPI 捆绑在一起的 Newtonsoft JSON Library,以正确序列化以下类:

public class SomeClass {
    [Required]
    public DateTime DateToBeSerialized { get; set; }

    [Required]
    public Dictionary<DateTime, long> DatesDict { get; set; }
}

序列化后输出如下JSON:

"DateToBeSerialized": "2013-03-07T19:03:22.5432182Z",
"DatesDict": {
    "12/01/2012 00:00:00": 593,
    "01/01/2013 00:00:00": 691,
    "02/01/2013 00:00:00": 174,
    "03/01/2013 00:00:00": 467
}

如您所见,当对象为 type DateTime 时,序列化程序遵循我的DateTime 的格式,但在序列化KeyValuePair&lt;DateTime, long&gt; 的关键部分。

换句话说,我希望序列化器输出:

"DateToBeSerialized": "2013-03-07T19:03:22.5432182Z",
"DatesDict": {
    "2012-12-01T00:00:00.0000000Z": 593,
    "2013-01-01T00:00:00.0000000Z": 691,
    "2013-02-01T00:00:00.0000000Z": 174,
    "2013-03-01T00:00:00.0000000Z": 467
}

我希望社区可以就如何解决此问题提供任何建议。

【问题讨论】:

  • 您添加到 DatesDict 的 DateTime 键值不是您想要的日期时间格式。

标签: json json.net asp.net-web-api


【解决方案1】:

这已在 JSON.Net 5.0 release 1(2013 年 4 月 7 日)中得到纠正。如果你更新到latest version,你应该已经准备好了。

这是我用来验证的测试代码:

SomeClass sc = new SomeClass();
sc.DateToBeSerialized = new DateTime(2013, 3, 7, 19, 3, 22, 543, DateTimeKind.Utc);
sc.DatesDict = new Dictionary<DateTime, long>();
sc.DatesDict.Add(new DateTime(2012, 12, 1, 0, 0, 0, 1, DateTimeKind.Utc), 593);
sc.DatesDict.Add(new DateTime(2013, 1, 1, 0, 0, 0, 2, DateTimeKind.Utc), 691);
sc.DatesDict.Add(new DateTime(2013, 2, 1, 0, 0, 0, 3, DateTimeKind.Utc), 174);
sc.DatesDict.Add(new DateTime(2013, 3, 1, 0, 0, 0, 4, DateTimeKind.Utc), 467);

string json = JsonConvert.SerializeObject(sc, Formatting.Indented);
Console.WriteLine(json);

输出:

{
  "DateToBeSerialized": "2013-03-07T19:03:22.543Z",
  "DatesDict": {
    "2012-12-01T00:00:00.001Z": 593,
    "2013-01-01T00:00:00.002Z": 691,
    "2013-02-01T00:00:00.003Z": 174,
    "2013-03-01T00:00:00.004Z": 467
  }
}

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 2023-03-10
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    相关资源
    最近更新 更多