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;
})
ConfigureHttpJsonOptionsandAddJsonOptionsmanage serilizer settings for model binding/response serialization, they will not affect the settings you use to deserialize manually. Provide settings forJsonSerializer.Deserialize, for example:Notes
There is no need to explicitly configure JSON options for API to only set the
PropertyNameCaseInsensitivetotruesinceJsonSerializerDefaults.Webdefaults toPropertyNameCaseInsensitive = true:You can resolve configured JSON options from the DI. For example for minimal APIs (or you can configure your own and resolve them):
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");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.