I use .NET6 and Blazor. I read same data from an API. To convert the JSON I use System.Text.Json
. In the JSON I expect a list of float/decimal but in same cases instead of a list of numbers there is the string "NA"
.
In this case, the conversion fails and there is an exception on this line
return JsonSerializer.Deserialize<APIResponse>(responseContent);
I saw that with JSON.NET it is possible to write some custom code to avoid this error. An example is
Root obj = JsonConvert.DeserializeObject<Root>(
json, new JsonSerializerSettings
{
Error = (sender, args) =>
{
Reading reading = args.CurrentObject as Reading;
if (reading != null && args.ErrorContext.Member.ToString() == "temperature")
{
reading.Temperature = null;
args.ErrorContext.Handled = true;
}
}
});
but there is nothing similar on System.Text.Json
.
How can I fix it?
Error handling is not implemented in
System.Text.Json
You can follow the issue here: https://github.com/dotnet/runtime/issues/38049