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.
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.
This works.
JsonSerializerOptions default = new JsonSerializerOptions(JsonSerializerDefaults.Web).ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.