【问题标题】:How to return json date from C# DateTime如何从 C# DateTime 返回 json 日期
【发布时间】:2016-07-25 13:53:07
【问题描述】:

我正在使用 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))]

【问题讨论】:

标签: c# json wcf datetime json.net


【解决方案1】:

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

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

祝你好运

【讨论】:

    【解决方案2】:

    尝试[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter)) 或按照Parsing JSON DateTime from Newtonsoft's JSON Serializer 中的说明使用 CustomDateConverter

    【讨论】:

    • Json.NET 默认返回 ISO 8601 日期格式多年。您链接到的问题是非常旧的,不再适用。
    • 谢谢。很高兴知道。
    猜你喜欢
    • 2013-01-18
    • 2018-12-26
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多