Controlling DateTime Format in JSON Output with JsonSerializerOptions

By FoxLearn 1/14/2025 7:20:34 AM   26
When building APIs with .NET Core MVC, you may want to control how your data is serialized into JSON format.

You can solve by adding a custom JsonConverters to your controllers, which lets you modify the output for specific data types like DateTime.

In this example, we'll walk through how to configure a custom DateTime converter to format the date in a specific pattern when it is returned from a GET method in your Web API.

Configure JSON Options in Startup.cs

First, you'll need to configure the JsonSerializerOptions to enable custom formatting for your Web API. This is done by adding AddJsonOptions in the ConfigureServices method of your Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddJsonOptions(options =>
    {
        // Add any additional converters here
    });
}

This ensures that when clients request data with application/json, the output will be formatted as JSON.

Create a Custom DateTime Converter

Next, create a custom JsonConverter that will control how DateTime objects are serialized. In this example, we'll format the DateTime output to yyyy-MM-ddTHH:mm:ss, which represents the date and time in a specific pattern.

Create a new class for the DateTimeConverter:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace MyApp.Converters
{
    public class DateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            // Parse the date string back into DateTime
            return DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            // Format the DateTime as 'yyyy-MM-ddTHH:mm:ss'
            writer.WriteStringValue(value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss"));
        }
    }
}

This DateTimeConverter defines two key methods:

  • Read: Converts a JSON date string back into a DateTime object.
  • Write: Converts a DateTime object to a string formatted as yyyy-MM-ddTHH:mm:ss before being written to JSON.

Register the Custom Converter

Now that the custom converter is in place, you need to add it to the JsonSerializerOptions in your ConfigureServices method. This tells the application to use the custom converter when serializing and deserializing DateTime objects.

Update your ConfigureServices method to include the custom DateTimeConverter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddJsonOptions(options =>
    {
        // Add the custom DateTime converter
        options.JsonSerializerOptions.Converters.Add(new MyApp.Converters.DateTimeConverter());
    });
}

Now, when your Web API returns a DateTime object as part of a JSON response, it will be serialized using the custom format. For instance, a DateTime value of September 15, 2019, 10:30:00 PM will be returned as:

{
    "date": "2019-09-15T22:30:00"
}

This gives you complete control over how DateTime values are formatted when serialized into JSON, allowing you to maintain consistency in your API's responses.

By using custom converters like the DateTimeConverter, you can control how data is serialized and deserialized in your .NET Core MVC Web API. This flexibility allows you to ensure that your JSON output meets specific formatting requirements, making it easier to work with APIs across different systems.