使用DataContractJsonSerializer自定义DateTime序列化/反序列化

时间:2015-02-26 16:53:45

标签: c# json serialization deserialization

如何使用DateTime为对象图中的所有DataContractJsonSerializer属性将默认的JSON DateTime序列化/反序列化更改为自定义格式?

Json.Net库处理这个问题,但我不能在这个项目中使用它。

我尝试IDataContractSurrogate但我无法访问该值 - > DateTimes的字符串转换。

模型和预期的JSON是:

[DataContract]
public class Client
{
    [DataMember(Name = "id")]
    public int Id {get; set; }
    [DataMember(Name = "name")]
    public string Name {get; set; }
    [DataMember(Name = "contacts")]
    public IList<Contact> Contacts {get; set; }
    [DataMember(Name = "created")]
    public DateTime Created {get; set; }
    [DataMember(Name = "changed")]
    public DateTime Changed {get; set; }
}

[DataContract]
public class Contact
{
    [DataMember(Name = "name")]
    public string Name {get; set; }
    [DataMember(Name = "created")]
    public DateTime Created {get; set; }
}

{
    "id": 123,
    "name": "Client Name",
    "contacts": [
        {
            "name": "Contact Name",
            "created": "2014-01-25 02:12:43"
        }
    ],
    "created": "2014-01-25 01:11:23"
    "changed": "2014-01-25 03:22:41"
}

1 个答案:

答案 0 :(得分:5)

我可能会遗漏某些内容,但在创建序列化程序时尝试在设置中传递所需的日期和时间格式:

var serializer = new DataContractJsonSerializer(
    typeof(Client),
    new DataContractJsonSerializerSettings {
        DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
    });