我正在尝试获取 Newtonsoft JSON Library ,与 .NET 4.5 中的 WebAPI 捆绑在一起,以正确序列化以下类:
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
}
如您所见,Serializer 遵循我的 DateTime
的格式当对象是类型 DateTime
, 但在序列化 KeyValuePair<DateTime, long>
的关键部分时未能这样做.
换句话说,我希望序列化器输出:
"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
}
我希望社区可以就如何解决此问题提供任何建议。
最佳答案
这已在 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
}
}
关于json - 控制 KeyValuePair<DateTime, long> 键的序列化格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15279655/