I'm trying to deserialize JSON from API response into a model using .NET built-in JsonSerializer. I'm also using JsonUnmappedMemberHandling.Disallow to make sure I deserialize everything the JSON has. When the serializer encounters something it cannot map, it throws exceptions with messages like this:
code
JsonException: The JSON value could not be converted to CostEntity. Path: $.entities[6].currency | LineNumber: 0 | BytePositionInLine: 4540.
That one means my enum Currency does not have a value matching the one from currency field somewhere in JSON, but I don't know what the exact value is unless I manually search entire JSON and compare it with my enum's definition. Is there a way to display the exact value that caused the deserialization to fail?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Yes, you can achieve this by catching the JsonException and inspecting its properties.
The JsonException thrown by System.Text.Json.JsonSerializer contains a Path property that indicates the location of the error in the JSON document. However, it does not directly expose the actual JSON value that caused the error.
To get the exact value, you'll need to:
Catch the JsonException.
Use a Utf8JsonReader to read the JSON document and navigate to the error location specified by the Path property.
Extract the value at that location.
Here's an example implementation:
csharp
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class JsonDeserializationHelper
{
public static object DeserializeWithErrorDetails(string json, Type targetType)
{
try
{
return JsonSerializer.Deserialize(json, targetType, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
});
}
catch (JsonException ex)
{
var errorValue = GetJsonValueAtErrorLocation(json, ex);
throw new JsonException($"Error at {ex.Path}: {errorValue}. {ex.Message}", ex);
}
}
private static string GetJsonValueAtErrorLocation(string json, JsonException ex)
{
var jsonDoc = JsonDocument.Parse(json);
var pathSegments = ex.Path.TrimStart('$').Split('.');
JsonElement currentElement = jsonDoc.RootElement;
foreach (var segment in pathSegments)
{
// Handle array indices (e.g., "entities[6]")
if (segment.Contains("["))
{
var propertyName = segment.Split('[')[0];
var index = int.Parse(segment.Split('[')[1].TrimEnd(']'));
if (currentElement.TryGetProperty(propertyName, out JsonElement arrayElement) &&
arrayElement.ValueKind == JsonValueKind.Array &&
index < arrayElement.GetArrayLength())
{
currentElement = arrayElement[index];
}
else
{
// If we can't navigate to the exact location, return a hint
return $"Unable to navigate to '{ex.Path}'. JSON structure might have changed.";
}
}
else
{
if (!currentElement.TryGetProperty(segment, out currentElement))
{
// If we can't navigate to the exact location, return a hint
return $"Unable to navigate to '{ex.Path}'. JSON structure might have changed.";
}
}
}
// We've reached the error location; return the JSON value as a string
return currentElement.ToString();
}
}
Example usage:
csharp
public enum Currency { USD, EUR, GBP }
public class Entity
{
public Currency Currency { get; set; }
}
public class Response
{
public Entity[] Entities { get; set; }
}
class Program
{
static void Main()
{
var json = @"
{
""entities"": [
{ ""currency"": ""USD"" },
{ ""currency"": ""InvalidCurrency"" } // This will cause the error
]
}";
try
{
var response = (Response)JsonDeserializationHelper.DeserializeWithErrorDetails(json, typeof(Response));
Console.WriteLine("Deserialization successful.");
}
catch (JsonException ex)
{
Console.WriteLine(ex.Message);
}
}
}
In this example, when you run the Main method, the output will be:
code
Error at $.entities[1].currency: "InvalidCurrency". The JSON value could not be converted to Currency. Path: $.entities[1].currency | LineNumber: 0 | BytePositionInLine: 64.
Now you can see the exact value ("InvalidCurrency") that caused the deserialization error.
Note: This implementation assumes that the JSON structure hasn't changed significantly since the error was reported. If the JSON structure has changed (e.g., an array became an object), the GetJsonValueAtErrorLocation method might not be able to navigate to the exact error location and will return a hint message instead. You can enhance this method to handle such cases if needed.