问题描述
对于对象图中的所有DateTime
属性,如何使用DataContractJsonSerializer
将默认的JSON DateTime
序列化/反序列化更改为自定义格式?
How to change the default JSON DateTime
serialization/deserialization to a custom format using DataContractJsonSerializer
for all DateTime
properties in the object graph?
Json.Net库处理了这个问题,但是我不能在这个项目中使用它.
The Json.Net library deals with this but I can't use that in this project.
我尝试了IDataContractSurrogate
,但是我无法访问值-> DateTimes的字符串转换.
I tried IDataContractSurrogate
but I cannot access the value -> string conversion for DateTimes.
模型和预期的JSON是:
The model and expected JSON are:
[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"
}
推荐答案
我可能遗漏了一些东西,但是在创建序列化程序时尝试在设置中传递所需的日期和时间格式:
I might be missing something, but try passing the desired date and time format in the settings when creating the serializer:
var serializer = new DataContractJsonSerializer(
typeof(Client),
new DataContractJsonSerializerSettings {
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
});
这篇关于使用DataContractJsonSerializer的自定义DateTime序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!