k3davis
k3davis

Reputation: 1105

Deserializing NodaTime Instant from System.Text.Json

I'm using Noda Time in an ASP.NET Core project and a model that contains two Instant properties.

public class Template
{
    //... redacted bits

    public Instant CreateDt { get; set; }
    public Instant LastmodDt { get; set; }
}

The info in the database is as I expect "out of box." However getting back the values via API returns empty object properties like this:

{
    //... redacted bits

    "createDt": {},
    "lastmodDt": {}
}

How do I get back the same date I put in, or at least some data I can massage into it?

FWIW I'm using ASP.NET Core 3.1, with the default System.Text.Json (not JSON.NET).

Edit: Removed spurious notes about PostgreSQL which turned out to be irrelevant to the question.

Upvotes: 8

Views: 3197

Answers (1)

k3davis
k3davis

Reputation: 1105

I was able to resolve this with an assist noted in the comments, by installing the NodaTime.Serialization.SystemTextJson package and adding this to my Startup.cs:

services.AddControllers()
    // the added bit:
    .AddJsonOptions(opt => opt.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));

I had to reverse-engineer this from other uses found on github since I was looking at the wrong version of the userguide for NodaTime like a doofus. Cheers.

Upvotes: 22

Related Questions