Home > other >  Custom json converter not working correctly asp.net core api blazor
Custom json converter not working correctly asp.net core api blazor

Time:08-03

I have a custom converter for one of my object :

public class FooConverter : JsonConverter<Foo>
{
    public override bool CanConvert( Type typeToConvert )
    {
        return typeof( Foo ).IsAssignableFrom( typeToConvert );
    }

    public override Foo? Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options )
    {
        using var jsonDoc = JsonDocument.ParseValue( ref reader );
        return jsonDoc.RootElement.GetPropertyCaseInsensitive( "Type" ).GetString() switch
        {
            nameof( TFoo) => jsonDoc.RootElement.Deserialize<TFoo>( options ),
            nameof( PFoo) => jsonDoc.RootElement.Deserialize<PFoo>( options ),
            _ => throw new JsonException( "'Type' doesn't match a known derived type" ),
        };
    }

    public override void Write( Utf8JsonWriter writer, Foomethod, JsonSerializerOptions options )
    {
        JsonSerializer.Serialize( writer, (object) foo, options );        
    }
}

When calling the api from blazor using the httpClient like this :

        List<Foo>? foos= await _httpClient.GetFromJsonAsync<List<Foo>>( "api/Foo" );

With the server like this :

   List<Foo> foos= await fooservice.GetFoos(); // This is not empty
        return Ok( foos );

I receive a null response from the server (which is not the case in postman), but when I do it like this, i receive the response correctly :

  List<Foo> foos= await fooservice.GetFoos(); // This is not empty
        return Ok( JsonSerializer.Serialize( foos) );

even though, I have those in startup.cs

services.AddControllers();
        .AddJsonOptions( j =>
        {
           var options = new JsonSerializerOptions();
            options.Converters.Add( new FooConverter() );
        } );

Am I missing something?

CodePudding user response:

The First element of Converters is the default converter,You could try

services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.Converters.Insert(0, new FooConverter()));

Got into the Write Method successfully:

enter image description here

CodePudding user response:

In your startup you are creating a new JsonSerializerOptions instead of configuring the provided options.

Try:

services
    .AddControllers()
    .AddJsonOptions(o =>
    {
        o.JsonSerializerOptions.Converters.Add(new FooConverter());
    });
  • Related