Home > Mobile >  How to set JsonSerializer options in programm.cs in .net 6?
How to set JsonSerializer options in programm.cs in .net 6?

Time:08-25

I want to use the default jsonSerializer (not the from newtsoft) and this is my working code:

    WsRequest request = JsonSerializer.Deserialize<WsRequest>(data, new JsonSerializerOptions
{
    Encoder = JavaScriptEncoder.Default,
    IncludeFields = true,
});

Now I want to have the options set globaly, I tried this:

 var host = Host.CreateDefaultBuilder(args);
    host.ConfigureLogging((context, builder) => builder.AddConsole());
    host.ConfigureServices((context, services) =>
    {
        services.Configure<JsonSerializerOptions>(options =>
        {
            options.Encoder = JavaScriptEncoder.Default;
            options.IncludeFields = true;
        });
        
        // Controller
        services.AddTransient<IWsPost<LoginPostModel>, LoginController>();
        services.AddTransient<IWsPostPublic<RegistrationPostModel>, RegistrationController>();
        services.AddTransient<IWsPostPublic<NewPasswordPostModel>, NewPasswordController>();
        
        // Others
        services.AddTransient<IWsApiManager, WsApiManager>();
        services.AddTransient<IWsClient, WsClient>();
        services.AddHostedService<WsServerService>();
    });
    await host.RunConsoleAsync();

And

 WsRequest request = JsonSerializer.Deserialize<WsRequest>(data);

but then the outcome is that the settings are not used - why this?

CodePudding user response:

From what I know, the JsonSerializerOptions set in 'program.cs' is only used in pages when returning a JsonResult and when binding Json data from a form.

It does not set a global option for JsonSerializer static methods.

To use it globally I have created a public static property, which I can then add where ever I want.

  • Related