Home >Backend Development >C++ >How to Specify Custom Date Formats for DateTime Serialization in Json.Net without Global Settings?

How to Specify Custom Date Formats for DateTime Serialization in Json.Net without Global Settings?

Barbara Streisand
Barbara StreisandOriginal
2025-01-16 00:01:47551browse

How to Specify Custom Date Formats for DateTime Serialization in Json.Net without Global Settings?

Json.Net custom DateTime serialized date format

Question:

When using Json.Net serialization in ASP.NET Web API, how to specify a custom date format while avoiding modifying global settings to meet the needs of a specific application?

Answer:

The recommended approach is to use a custom JsonConverter for selective formatting. Json.Net provides an IsoDateTimeConverter that allows custom formatting. Since the format cannot be set directly through the JsonConverter property, you can create a subclass and specify the desired format in its constructor. A custom converter can then be applied to a specific property using the JsonConverter property:

<code class="language-csharp">class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy'-'MM'-'dd";
    }
}

class ReturnObjectA 
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ReturnDate { get; set; }
}</code>

If you do not need the time format, you can directly apply the default date format of IsoDateTimeConverter:

<code class="language-csharp">[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime ReturnDate { get; set; }</code>

The above is the detailed content of How to Specify Custom Date Formats for DateTime Serialization in Json.Net without Global Settings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn