【问题标题】:Dates without time in ASP.NET Web API's JSON outputASP.NET Web API JSON 输出中没有时间的日期
【发布时间】:2013-04-25 14:31:34
【问题描述】:

有没有一种简单的方法来配置 JSON.NET,以便 一些 DateTime 字段将不带时间格式化,而其他 DateTime 字段仍将带时间格式化?

例子:

{ firstName: 'John', lastName : 'Doe', birthday: '1965-09-23' }

【问题讨论】:

    标签: json datetime asp.net-web-api json.net


    【解决方案1】:

    尝试添加此行来配置您的 Web API:

    config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
        new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd" });
    

    【讨论】:

    • 这将在全球范围内产生影响,而不仅仅是按要求对“某些”字段产生影响。
    【解决方案2】:

    如果您需要它只影响特定字段,请先创建转换器类型:

    public class OnlyDateConverter : IsoDateTimeConverter
    {
        public OnlyDateConverter()
        {
            DateTimeFormat = "yyyy-MM-dd";
        }
    }
    

    然后将此属性添加到您想要的任何字段/属性:

    [JsonConverter(typeof(OnlyDateConverter))]
    

    【讨论】:

    • 不错。我刚开始写同样的东西,但扩展了DateTimeConverterBase。这样干净多了!
    • 正是我需要的!非常感谢优素福!
    • 显然你应该使用/而不是破折号来为某些旧浏览器带来好处:blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html
    • 也可以使用Microsoft.Rest.ClientRuntime包中预定义的Microsoft.Rest.Serialization.DateJsonConverter类型(与Microsoft.AspNetCore.All包一起安装)
    • 这对我不起作用,即使我用这个属性装饰模型的属性,我仍然会收到时间。
    【解决方案3】:

    Yousesef 用OnlyDateConverter 回答是最好的。但这里有另一种选择:

    private DateTime _birthday;
    public string Birthday
    {
        get { return _birthday.ToString("yyyy-MM-dd"); }
        set {
              _birthday = DateTime.ParseExact(value, "yyyy-MM-dd",
                                              CultureInfo.InvariantCulture);
            }
    }
    

    优势 - 您无需将 Newtonsoft.Json 库绑定到您的类。

    缺点 - 该属性现在在您使用它的任何地方都作为字符串公开,这可能会导致它自己的一系列问题。

    【讨论】:

    • 我已经考虑过这种方法,但是当日期之间可能涉及计算时,它可能不是最好的方法。无论如何,谢谢!
    猜你喜欢
    • 2012-11-28
    • 2016-02-03
    • 1970-01-01
    • 2013-08-10
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多