我试图获得与.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
时,Serializer会尊重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
}
我很乐意社区可以提供有关如何解决此问题的任何建议。
答案 0 :(得分:0)
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
}
}