Reputation: 1
Trying to set up a brand new .Net 5.0 API and the service runs, but I want to use NodaTime and I cannot figure out how to get the serialization settings to work. The below seems to be correct, but getting,
The JSON value could not be converted to NodaTime.LocalDate
when trying to send in
{
"date": "2021-Jan-01"
}
Here is my current config:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NodaTime;
using NodaTime.Serialization.JsonNet;
namespace src
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddJsonOptions(_ =>
{
new JsonSerializer()
.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
});
}
Upvotes: 0
Views: 783
Reputation: 1502126
Ideally, you'd use ISO-8601 dates instead (so "2021-01-01" instead of "2021-Jan-01"). That's the standardized way of representing a date, and it doesn't use culture-sensitive month names.
If you really need to use this format, you'd need to remove the LocalDate
converter populated by NodaTime.Serialization.JsonNet and add a new one.
You can copy the "replace converters with a new one" code from here - it's slightly unfortunate that you need to copy the code, but it's not something I really want to expose publicly.
Creating a new converter for LocalDate
is easy, fortunately:
var pattern = LocalDatePattern.CreateWithInvariantCulture("uuuu'-'MMM'-'dd");
var converter = new NodaPatternConverter<LocalDate>(pattern);
(That doesn't perform the validation that the LocalDate
is in the ISO calendar like the built-in converters do, but you're unlikely to need that.)
Upvotes: 1