6

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.

k3davis
  • 985
  • 12
  • 29
  • 2
    Have you installed and configured the NodaTime.Serialization.SystemTextJson package? (It's not clear how the database is involved here - I'd expect this to be reproducible without anything to do with the database, at which point your question could be simplified.) – Jon Skeet Sep 09 '20 at 14:27
  • @JonSkeet You are quite right. I didn't realize that I was looking at a previous version of the NodaTime user guide (from a Google search), and therefore couldn't find any reference to System.Text.Json serialization. Smooth on my part. Thanks for the lead. – k3davis Sep 09 '20 at 15:29
  • Cool. If you've got it working now, you might want to just add an answer. – Jon Skeet Sep 09 '20 at 15:42

1 Answers1

17

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.

k3davis
  • 985
  • 12
  • 29