0

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?

jjo
  • 2,595
  • 1
  • 8
  • 16
lolo xoxo
  • 31
  • 2

1 Answers1

0

I think you can refer to this link to modify your JsonConverter: How to use default serialization in a custom System.Text.Json JsonConverter?.

As mentioned in the link, you can't use [JsonConverter(typeof(YourConverter))] on your model, it will cause a StackOverflowException. You can add it globally as a converter:

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new YourConverter());
    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
Chen
  • 4,499
  • 1
  • 2
  • 9
  • can you provide the `YourConverter` as well? I cannot make it without generic approach. When I use T it's easier as I am calling `JsonSerializer.Deserialize` to get the exception and handle it further – lolo xoxo Apr 24 '23 at 10:35