Hec
Hec

Reputation: 33

System.Text.Json Custom JsonConverter never called

I wanted to migrate from Newtonsoft an Asp net core project. I must use a JsonConverter to keep some old functionality.

I have tried calling my custom converter on a property, on a type and on startup as I read in the docs; It never seems to be called.

I created a sample project just to be sure it was not something else. If the converter executes either the Write or Read methods it should throw an exception. But so far I have not been able to make them execute.

Here is the code for the converter

public class MyCustomConverter : JsonConverter<FooProp>
{
    public override FooProp Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options) => throw new NotImplementedException();

    public override void Write(
        Utf8JsonWriter writer,
        FooProp value,
        JsonSerializerOptions options) => throw new NotImplementedException();
}

The code of the controller

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    public WeatherForecastController()
    {
    }

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new FooClass());
    }

    public class FooClass
    {
        public string Always {get; set;}
        // Adds on property
        [JsonConverter(typeof(MyCustomConverter))]
        public FooProp Sometimes {get; set;}
    }

    // Adds on type
    [JsonConverter(typeof(MyCustomConverter))]
    public class FooProp
    {
        public string Something { get; set; }
    }
}

And the code for startup

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddControllers()
        .AddJsonOptions(options => {
            // Adds on startup
            options.JsonSerializerOptions.Converters.Add(new MyCustomConverter());
        });
}

The .csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
</Project>

It seems so simple, I must be doing an obvious mistake, but I have been at this for a while unable to find what im doing wrong.

Can anyone help me?

Upvotes: 3

Views: 3975

Answers (1)

Rena
Rena

Reputation: 36715

I have tried calling my custom converter on a property, on a type and on startup as I read in the docs; It never seems to be called.

That is because your custom JsonConverter inherits the JsonConverter<FooProp> which can only convert FooProp class:

public class MyCustomConverter : JsonConverter<FooProp>

You returned new FooClass,it would create null Sometimes. Just change the following code then you could see the exception:

[HttpGet]
public IActionResult Get()
{
    //return Ok(new FooProp());
    return Ok(new FooClass { Sometimes = new FooProp() });
}

Upvotes: 3

Related Questions