json - 控制 KeyValuePair<DateTime, long> 键的序列化格式

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

我正在尝试获取 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/

相关文章:

c# - 在 OData 查询中使用复杂类型

asp.net-mvc - 如何从 Controller 为存储库的构造函数指定参数?

javascript - 为什么我不能从 url 中获取 json 对象

c# - 填充现有对象时在添加项目之前清除集合

c# - 为什么 JSON.NET 在我的 DataTable 中以这种格式输出 DateTime 值?

c# - json.net 列表序列化到 JSON 数组

javascript - 删除 JSON 的特定部分

javascript - 如何访问数组中的元素?

c# - JSON.net 将 C# 对象序列化为 JSON 问题

c# - Azure 是否限制了我的 WebApi?