C# 使用 Json.Net 序列化时指定自定义日期时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18635599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specifying a custom DateTime format when serializing with Json.Net
提问by Stay Foolish
I am developing an API to expose some data using ASP.NET Web API.
我正在开发一个 API 来使用 ASP.NET Web API 公开一些数据。
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.
在其中一个 API 中,客户希望我们以yyyy-MM-dd
格式公开日期。我不想为此更改全局设置(例如GlobalConfiguration.Configuration.Formatters.JsonFormatter
),因为它非常特定于此客户端。我确实在为多个客户的解决方案中开发它。
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
我能想到的解决方案之一是创建一个自定义JsonConverter
,然后将其放入我需要进行自定义格式设置的属性中
e.g.
例如
class ReturnObjectA
{
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime ReturnDate { get;set;}
}
Just wondering if there is some other easy way of doing that.
只是想知道是否有其他简单的方法可以做到这一点。
采纳答案by Brian Rogers
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:
你走在正确的轨道上。既然你说你不能修改全局设置,那么下一个最好的办法是JsonConverter
根据你的建议根据需要应用该属性。事实证明 Json.Net 已经有一个内置的IsoDateTimeConverter
,可以让你指定日期格式。不幸的是,您不能通过JsonConverter
属性设置格式,因为属性的唯一参数是类型。但是,有一个简单的解决方案:将 子类化IsoDateTimeConverter
,然后在子类的构造函数中指定日期格式。JsonConverter
在需要的地方应用属性,指定您的自定义转换器,然后就可以开始了。这是所需的全部代码:
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
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).
如果您不介意也有时间,您甚至不需要对 IsoDateTimeConverter 进行子类化。它的默认日期格式是yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(如源代码所示)。
回答by Saeb Amini
It can also be done with an IsoDateTimeConverter
instance, without changing global formatting settings:
也可以使用IsoDateTimeConverter
实例完成,而无需更改全局格式设置:
string json = JsonConvert.SerializeObject(yourObject,
new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
This uses the JsonConvert.SerializeObject
overload that takes a params JsonConverter[]
argument.
这使用了JsonConvert.SerializeObject
带params JsonConverter[]
参数的重载。
回答by Matt
Also available using one of the serializer settings overloads:
也可以使用序列化器设置重载之一:
var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Or
或者
var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });
Overloads taking a Type are also available.
也可以使用 Type 的重载。
回答by Keith Hill
You could use this approach:
您可以使用这种方法:
public class DateFormatConverter : IsoDateTimeConverter
{
public DateFormatConverter(string format)
{
DateTimeFormat = format;
}
}
And use it this way:
并以这种方式使用它:
class ReturnObjectA
{
[JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
public DateTime ReturnDate { get;set;}
}
The DateTimeFormat string uses the .NET format string syntax described here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
DateTimeFormat 字符串使用此处描述的 .NET 格式字符串语法:https: //docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
回答by Xin
Build helper class and apply it to your property attribute
构建辅助类并将其应用于您的属性属性
Helper class:
辅助类:
public class ESDateTimeConverter : IsoDateTimeConverter
{
public ESDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
}
}
Your code use like this:
您的代码使用如下:
[JsonConverter(typeof(ESDateTimeConverter))]
public DateTime timestamp { get; set; }
回答by Muni Chittem
Some times decorating the json convert attribute will not work ,it will through exception saying that "2010-10-01" is valid date. To avoid this types i removed json convert attribute on the property and mentioned in the deserilizedObject method like below.
有时装饰 json 转换属性不起作用,它会通过异常说“ 2010-10-01”是有效日期。为了避免这种类型,我删除了属性上的 json convert 属性,并在 deserilizedObject 方法中提到,如下所示。
var addresss = JsonConvert.DeserializeObject<AddressHistory>(address, new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });
回答by Antonio Rodríguez
There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.
我一直在使用另一种解决方案。只需创建一个字符串属性并将其用于 json。此属性将返回格式正确的日期。
class JSonModel {
...
[JsonProperty("date")]
public string MyDate { get; set; }
public string CustomDate {
get { return MyDate.ToString("DDMMYY"); }
set { MyDate = DateTime.Parse(value); }
}
...
}
This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.
这样您就不必创建额外的类。此外,它还允许您创建不同的数据格式。例如,您可以使用相同的日期时间轻松地为小时创建另一个属性。