使用Json.Net使用dd / MM / yyyy反序列化嵌套日期

时间:2017-03-15 16:34:41

标签: c# json date serialization

这似乎与Deserializing dates with dd/mm/yyyy format using Json.Net的重复相似,但建议的解决方案似乎对我不起作用。

我有一个测试用例

void Main()
{
    if (File.Exists("config.json"))
    {
        string json = File.ReadAllText("config.json");
        var dateTimeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" };
        PositionForwardingConfiguration config = Newtonsoft.Json.JsonConvert.DeserializeObject<PositionForwardingConfiguration>(json, dateTimeConverter);
        foreach (var client in config.ClientConfiguration.clients)
        {
            Debug.WriteLine(string.Format("Date: {0}", client.MiniumDate));
        }
        json = Newtonsoft.Json.JsonConvert.SerializeObject(config, dateTimeConverter);
        Debug.WriteLine(json);
    }

}
public class PositionForwardingConfiguration
{
    public ClientConfiguration ClientConfiguration { get; set; }
}

public class ClientConfiguration
{
    public ClientInfo[] clients { get; set; }
}
public class ClientInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime MiniumDate { get; set; }
    public string Token { get; set; }
    public Uri Endpoint { get; set; }
}

产生类似

的输出
Date: 1/1/0001 12:00:00 AM
Date: 1/1/0001 12:00:00 AM
Date: 1/1/0001 12:00:00 AM
{"ClientConfiguration":{"clients":[{"Id":1,"Name":"1","MiniumDate":"01/01/0001","Token":"Token 1","Endpoint":"http://1"},{"Id":2,"Name":"2","MiniumDate":"01/01/0001","Token":"Token 2","Endpoint":"http://2"},{"Id":3,"Name":"3","MiniumDate":"01/01/0001","Token":"Token 3","Endpoint":"http://3"}]}}

特别注意,日期不是使用提供的转换器进行反序列化或序列化。有没有改变Newtonsoft.JSON的东西使这不起作用?我的输入看起来像

{
    "ClientConfiguration": {
        "clients": [
        {
            "Id" : 1,
            "Name" : "1",
            "MinimumDate" : "01/01/2017",
            "Token" : "Token 1",
            "Endpoint" : "http://1"
        },
        {
            "Id" : 2,
            "Name" : "2",
            "MinimumDate" : "02/01/2017",
            "Token" : "Token 2",
            "Endpoint" : "http://2"
        },
        {
            "Id" : 3,
            "Name" : "3",
            "MinimumDate" : "03/01/2017",
            "Token" : "Token 3",
            "Endpoint" : "http://3"
        }
      ]
    }
}

想法?

0 个答案:

没有答案