问题描述
我正在开发一个 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.
我能想到的解决方案之一是创建一个自定义 JsonConverter
,然后将其放入我需要进行自定义格式设置的属性
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;}
}
只是想知道是否有其他简单的方法可以做到这一点.
Just wondering if there is some other easy way of doing that.
推荐答案
你在正确的轨道上.既然你说你不能修改全局设置,那么下一个最好的事情是根据需要应用 JsonConverter
属性,正如你所建议的那样.原来 Json.Net 已经有一个内置的 IsoDateTimeConverter
可让您指定日期格式.不幸的是,您不能通过 JsonConverter
属性设置格式,因为该属性的唯一参数是一个类型.但是,有一个简单的解决方案:将 IsoDateTimeConverter
子类化,然后在子类的构造函数中指定日期格式.在需要的地方应用 JsonConverter
属性,指定您的自定义转换器,然后您就可以开始了.以下是所需的全部代码:
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";
}
}
如果您不介意也有时间,您甚至不需要子类化 IsoDateTimeConverter.它的默认日期格式是 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).
这篇关于使用 Json.Net 序列化时指定自定义 DateTime 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!