.NET Core MVC Web API – control DateTime format in JSON output using JsonSerializerOptions

When creating API’s with .NET Core MVC, you can control the JSON output by adding JsonOptions to the controllers:

public void ConfigureServices(IServiceCollection services)
{
  ...
  ...
  services.AddControllers().AddJsonOptions();
  ...
  ...
}

This will ensure that when requesting application/json from a GET method, the format returned is JSON.

You can then add Converters to the configuration, controlling the default behavior of the JSON. This is a DateTime converter, forcing any DateTime type to be outputted as “2019-15-09Y22:30:00

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

namespace MyCode.Converters
{
  public class DateTimeConverter : JsonConverter<DateTime>
  {
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
      return DateTime.Parse(reader.GetString());
    }

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

The converter needs to be added to my configuration:

public void ConfigureServices(IServiceCollection services)
{
  ...
  ...
  services.AddControllers().AddJsonOptions(options =>
    {
      options.JsonSerializerOptions.Converters.Add(new Converters.DateTimeConverter());
    }
  );
  ...
  ...
}

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c# and tagged , , , , . Bookmark the permalink.

1 Response to .NET Core MVC Web API – control DateTime format in JSON output using JsonSerializerOptions

  1. gorhal says:

    Yes System.Text.Json is very nice :)
    Good post!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.