与Json.Net序列化时指定的自定义DateTime格式 [英] Specifying a custom DateTime format when serializing with Json.Net

查看:634
本文介绍了与Json.Net序列化时指定的自定义DateTime格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个API使用的ASP.NET Web API暴露一些数据。

I am developing an API to expose some data using ASP.NET Web API.

在API之一,客户希望我们揭露YYYY-MM-dd格式的日期。我不想改变,全球的设置(例如 GlobalConfiguration.Configuration.Formatters.JsonFormatter ),因为它是非常具体的此客户端。而且我不开发,在为多个客户的解决方案。

In one of the API, the client wants us to expose the date in yyyy-MM-dd format. I don't want to change the global settings (e.g. GlobalConfiguration.Configuration.Formatters.JsonFormatter) for that since it is very specific to this client. And I do developing that in a solution for multiple clients.

一,我能想到的解决方案是创建一个自定义的Json转换器,然后把那个给我财产需要做自定义格式

One of the solution that I could think of is to create a custom Json converter and then put that to the property I need to do the custom formatting

例如

Class ReturnObjectA 
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ReturnDate { get;set;}
}

只是不知道是否有这样做的其他一些简单的方法。

Just wondering if there is some other easy way of doing that.

推荐答案

您是在正确的轨道上。既然你说你不能修改全局设置,那么接下来最好的事情是应用在需要的基础上, JsonConverter 属性,如你所说。事实证明Json.Net已经有一个内置的<一href=\"http://james.newtonking.com/projects/json/help/?topic=html/T_Newtonsoft_Json_Converters_IsoDateTimeConverter.htm\"><$c$c>IsoDateTimeConverter让您指定的日期格式。不幸的是,你不能设置通过 JsonConverter 属性的格式,因为属性的唯一的参数是一个类型。幸运的是,解决方法很简单:子类 IsoDateTimeConverter ,然后指定日期的格式在子类的构造函数。应用在需要的地方,并指定您的自定义转换器 JsonConverter 属性,你准备好去。这里需要code的全部:

You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. Fortunately, the solution is simple: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:

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

如果你不介意在那里还的时候,你甚至都不需要继承的IsoDateTimeConverter。它的默认日期格式为: YYYY' - 'MM' - 'dd'T'HH':'毫米':'ss.FFFFFFFK (如被看见在<一个href=\"http://json.$c$cplex.com/SourceControl/latest#trunk/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs\">source code )。

If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).

这篇关于与Json.Net序列化时指定的自定义DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆