使用 Json.Net 序列化时指定自定义日期时间格式 [英] Specifying a custom DateTime format when serializing with Json.Net

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

问题描述

我正在开发一个 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 序列化时指定自定义日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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