Vitalii Isaenko
Vitalii Isaenko

Reputation: 999

How to setup nodatime json serializer in asp.net core 3.1

I try to figure out how to setup NodaTime JSON serialization in ASP.NET Core 3.1 Web Api project. The way it is described here doesn't work for me

services.AddJsonFormatters(settings => settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));

because there is no such method as AddJsonFormatters on services : IServiceCollection.
Installed packages:

NodaTime v 3.0.3  
NodaTime.Serialization.JsonNet v 3.0.0
Microsoft.AspNetCore.Mvc.NewtonsoftJson v 3.1.9
Newtonsoft.Json v 12.0.3

Could you help me with this, please? What method should I use in Startup.cs to configure NodaTime?

Upvotes: 0

Views: 2447

Answers (2)

Daniel R
Daniel R

Reputation: 1273

Add Nuget Package "NodaTime.Serialization.SystemTextJson"

then do the following

 using NodaTime.Serialization.SystemTextJson;

....

.AddJsonOptions(options =>
        {               
            options.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
        });

Upvotes: 3

Vitalii Isaenko
Vitalii Isaenko

Reputation: 999

I was looking for the JsonSerializerSettings class that has the needed extension method ConfigureForNodaTime() and found it in SerializerSettings field of MvcNewtonsoftJsonOptions and configured it as below:

services.AddControllers().AddNewtonsoftJson(s =>
    s.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));

Upvotes: 6

Related Questions