Tomas Sundvall
Tomas Sundvall

Reputation: 54

Custom JsonConverter added to JsonSerializerOptions.Converters not used by default

I have implemented a custom json converter for one of my classes since I want to use the constructor for deserialization.

I have added the custom converter to my Startup.cs class:

services.AddControllers()
.AddJsonOptions(opt => 
{
   opt.JsonSerializerOptions.WriteIndented = false;
   opt.JsonSerializerOptions.Converters.Add(new MyJsonConverter());
});

My custom json converter looks like this:

public class MyJsonConverter : JsonConverter<MyClass>
{
   ...
}

The problem is that when running

var result = await JsonSerializer.DeserializeAsync<RoleEntity[]>(json);

my custom json converter isn't triggered.

However, if instead specifying it explicitly like the following

var serializerOptions = new JsonSerializerOptions
{ 
   Converters = { new MyJsonConverter() }
};
var result = await JsonSerializer.DeserializeAsync<RoleEntity[]>(json, serializerOptions);

it works.

I just can't see what the problem is. Am I missing something trivial here?

Upvotes: 1

Views: 3548

Answers (1)

Joelius
Joelius

Reputation: 4329

This is the expected behaviour. When you use JsonSerializer.DeserializeAsync directly without specifying any options it, well, won't use any custom options. The options you add in are for MVC (see this answer). You need to either continue using it as you wrote or register options as singleton which you could then resolve/inject and use within your JsonSerializer.DeserializeAsync call.

To add a new singleton you can use IServiceCollection.AddSingleton.

There are many ways to get the result you want (singleton options is just one of them) but the important part of this answer is that the options you define with .AddJsonOptions will not be used for direct calls to JsonSerializer-methods.

Upvotes: 2

Related Questions