Reputation: 1238
How to configure NodaTime serialization for System.Text.Json in Blazor WASM .Net 6? In a WebApi you would do
builder.Services.AddControllers().AddJsonOptions(settings => settings.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));
but there are no controllers in Blazor WASM.
This does not work either:
builder.Services.Configure<JsonSerializerOptions>(options => options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb));
var options = new JsonSerializerOptions().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
and providing to HttpClient
does not work either.
Upvotes: 1
Views: 1056
Reputation: 129
This works.
JsonSerializerOptions default = new JsonSerializerOptions(JsonSerializerDefaults.Web).ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
Upvotes: 4
Reputation: 1662
This is a hack and a workaround, but I ended up using Newtonsoft for this
//Should work but doesn't
var options = new JsonSerializerOptions().ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
var customClassList = await Http1.GetFromJsonAsync<List<customClass>>($"api/CustomClass", options);
//First: Get the raw json string
var response = await Http1.GetAsync($"api/CustomClass");
var content = await response.Content.ReadAsStringAsync();
//Second: Deserialize with Newtonsoft
var settings = new JsonSerializerSettings();
settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
var customClassList = JsonConvert.DeserializeObject<List<CustomClass>>(content, settings);
//Doesn't work (System.Text.Json)
var customClassList = JsonSerializer.Deserialize<List<CustomClass>>(content, options);
I suspect this has something to do with Blazor/WASM since the above code is basically the default example for json and nodatime with System.Text.Json. However, I don't get any weird errors or exceptions with in my Blazor app. It just doesn't deserialize properly.
Upvotes: 0