JSON deserialization with line and byte error info
C#
using System;
using System.Text.Json;
static T ParseJson<T>(string json, string label = "payload")
{
try
{
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
}) ?? throw new JsonException("Deserialized to null.");
}
catch (JsonException ex)
{
throw new FormatException(
$"Invalid JSON in {label} at line {ex.LineNumber + 1}, position {ex.BytePositionInLine + 1}: {ex.Message}", ex);
}
}