Set system.text.json.jsonserializer globally minimal api

202 Views Asked by At

I'm using .NET 8 minimal API. I want to set the system.text.json.jsonserializer globally.

i don't want to pass the defaultSerializerSettings each time.


    public static T Deserialize<T>(this string json)
    {       
        return JsonSerializer.Deserialize<T>(json, defaultSerializerSettings);
    }

Please take a look at this url.

https://stackoverflow.com/questions/58331479/how-to-globally-set-default-options-for-system-text-json-jsonserializer

what i was trying to do:

This seemed to work for me, in StartUp.ConfigureServices:

services.AddControllers().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        options.JsonSerializerOptions.PropertyNamingPolicy=JsonNamingPolicy.CamelCase;
    });

and it's not working with the minimal api.

i need the same thing with the minimal api

its not working with the minimal api

.ConfigureHttpJsonOptions(options => {
      options.SerializerOptions.PropertyNameCaseInsensitive = true;
})
1

There are 1 best solutions below

21
Guru Stron On

ConfigureHttpJsonOptions and AddJsonOptions manage serilizer settings for model binding/response serialization, they will not affect the settings you use to deserialize manually. Provide settings for JsonSerializer.Deserialize, for example:

var res = JsonSerializer.Deserialize<WeatherForecast[]>(responseContent, 
    new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true
    });

Notes

  1. There is no need to explicitly configure JSON options for API to only set the PropertyNameCaseInsensitive to true since JsonSerializerDefaults.Web defaults to PropertyNameCaseInsensitive = true:

    The following options have different defaults for web apps:

    • PropertyNameCaseInsensitive = true
    • JsonNamingPolicy = CamelCase
    • NumberHandling = AllowReadingFromString
  2. You can resolve configured JSON options from the DI. For example for minimal APIs (or you can configure your own and resolve them):

    app.MapGet("/weatherforecast", (IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions> opts) =>
         {
             var serOpts = opts.Value.SerializerOptions;
             // ...
         });
    
    
  3. You should not need to deserialize data to just serialize it back again (in the shown code at least). Returning content should do the trick: return Results.Content(responseContent, "application/json");

  4. You can't mutate default serialization options (see this github comment for example), at least ATM, but you can define helper/extension methods which will use some global statically defined ones.