如何从C#DateTime返回json日期

时间:2016-07-25 13:53:07

标签: c# json wcf datetime json.net

我正在使用Json.NET/newtonsoft,我有以下C#类:

public class EntityDefinition
{
    [DataMember]
    public string CreatedBy { get; set; }
    [DataMember]
    [JsonProperty(ItemConverterType = typeof(IsoDateTimeConverter))]
    public DateTime CreatedOn { get; set; }
}

当我尝试在我的wcf中返回此类时,我得到以下JSON:

{
  "GetDefinitionResult": {
    "CreatedBy": "Dor",
    "CreatedOn": "/Date(1466428742000+0300)/"
   }
}

如何在没有“Date(”,仅表示毫秒或iso格式“yyy-mm-dd”

的情况下获取要解析的日期

我尝试使用JsonProperty转换器,但它仍然返回“Date()”

[JsonProperty(ItemConverterType = typeof(IsoDateTimeConverter))]

2 个答案:

答案 0 :(得分:1)

尝试[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))或使用CustomDateConverter,如Parsing JSON DateTime from Newtonsoft's JSON Serializer

中所述

答案 1 :(得分:1)

WCF默认使用DataContractSerializer来序列化/反序列化邮件,并且提到的日期格式是其默认格式。

如果您想更改WCF服务序列化/反序列化消息的方式,您应该替换服务行为中的一些内容(主要是IDispatchMessageFormatter)。但是,这里描述的时间太长了,有一个很棒的教程here

祝你好运