問題描述
我正在開發(fā)一個(gè) API 來使用 ASP.NET Web API 公開一些數(shù)據(jù).
I am developing an API to expose some data using ASP.NET Web API.
在其中一個(gè) API 中,客戶端希望我們以 yyyy-MM-dd
格式公開日期.我不想為此更改全局設(shè)置(例如 GlobalConfiguration.Configuration.Formatters.JsonFormatter
),因?yàn)樗浅L囟ㄓ谠摽蛻舳?我確實(shí)在為多個(gè)客戶開發(fā)解決方案.
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.
我能想到的解決方案之一是創(chuàng)建一個(gè)自定義 JsonConverter
,然后將其放入我需要進(jìn)行自定義格式設(shè)置的屬性
One of the solution that I could think of is to create a custom JsonConverter
and then put that to the property I need to do the custom formatting
例如
class ReturnObjectA
{
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime ReturnDate { get;set;}
}
只是想知道是否有其他簡(jiǎn)單的方法可以做到這一點(diǎn).
Just wondering if there is some other easy way of doing that.
推薦答案
你在正確的軌道上.既然你說你不能修改全局設(shè)置,那么下一個(gè)最好的事情是根據(jù)需要應(yīng)用 JsonConverter
屬性,正如你所建議的那樣.原來 Json.Net 已經(jīng)有一個(gè)內(nèi)置的 IsoDateTimeConverter
可讓您指定日期格式.不幸的是,您不能通過 JsonConverter
屬性設(shè)置格式,因?yàn)樵搶傩缘奈ㄒ粎?shù)是一個(gè)類型.但是,有一個(gè)簡(jiǎn)單的解決方案:將 IsoDateTimeConverter
子類化,然后在子類的構(gòu)造函數(shù)中指定日期格式.在需要的地方應(yīng)用 JsonConverter
屬性,指定您的自定義轉(zhuǎn)換器,然后您就可以開始了.以下是所需的全部代碼:
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. However, there is a simple solution: 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";
}
}
如果您不介意也有時(shí)間,您甚至不需要子類化 IsoDateTimeConverter.它的默認(rèn)日期格式是 yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(見 源代碼).
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).
這篇關(guān)于使用 Json.Net 序列化時(shí)指定自定義 DateTime 格式的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!