使用 DataContractJsonSerializer 的自定义 DateTime serialization/deserialization
Custom DateTime serialization/deserialization using DataContractJsonSerializer
如何使用对象图中所有 DateTime
属性的 DataContractJsonSerializer
将默认 JSON DateTime
serialization/deserialization 更改为自定义格式?
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"
}
我可能遗漏了一些东西,但请尝试在创建序列化程序时在设置中传递所需的日期和时间格式:
var serializer = new DataContractJsonSerializer(
typeof(Client),
new DataContractJsonSerializerSettings {
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
});
如何使用对象图中所有 DateTime
属性的 DataContractJsonSerializer
将默认 JSON DateTime
serialization/deserialization 更改为自定义格式?
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"
}
我可能遗漏了一些东西,但请尝试在创建序列化程序时在设置中传递所需的日期和时间格式:
var serializer = new DataContractJsonSerializer(
typeof(Client),
new DataContractJsonSerializerSettings {
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
});