I have this piece of code :
public class MyJsonConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
try
{
// Use a different overload of JsonSerializer.Deserialize that takes a JsonConverter parameter
return JsonSerializer.Deserialize(ref reader, typeToConvert, options);
}
catch (JsonException ex)
{
throw new JsonException($"Unsupported value type for {typeToConvert.Name} field", ex);
}
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, value.GetType(), options);
}
public override bool CanConvert(Type typeToConvert)
{
// Use the same approach as JsonSerializer.Deserialize to determine if the type is convertible
return !typeToConvert.IsInterface && !typeToConvert.IsAbstract && (typeToConvert.IsValueType ||
typeToConvert.GetConstructor(
Type.EmptyTypes) != null);
}
}
What I want is to try to parse json and if data type invalid and it can't convert instead of throwing default JsonException I want to override it. This converter throws StackOverflow exception due to the converter is calling itself recursively when it fails to deserialize the input. How can I fix it, any suggestions?