0

In a Blazor WASM app under .NET 7 I configure standard Json serializer options like so in Program.cs

builder.Services.Configure<JsonSerializerOptions>(options => {
  options.TypeInfoResolver = new PolymorphicAgentaDtoResolver();
  options.PropertyNameCaseInsensitive = true;
});

Later on in a service of the App I want to serialize an object with JsonSerializer.Serialize(...). The result doesn't use the defaults from above. My question is why the defaults aren't used.

If I inject IOptions<JsonSerializerOptions> via the constructor of the service and use them in the appropriate overload of JsonSerializer.Serialize(...) the result is correct.

Code

public async Task<List<ServiceauftragDto>> GetServiceAuftraege(AgentaDto dto) {
  string s = JsonSerializer.Serialize<AgentaDto>(dto);  // wrong
  s = JsonSerializer.Serialize(dto);                    // wrong
  s = JsonSerializer.Serialize(dto, dto.GetType());     // wrong
  s = JsonSerializer.Serialize(dto, dto.GetType(), injectedOptions.Value);    // correct
  s = JsonSerializer.Serialize(dto, JsonSerializerOptions.Default);   // wrong
  ...
}
Jens Mander
  • 430
  • 7
  • 15
  • 1
    What you’re saying in the builder is _hey, when you’re asked to inject serialization options, please inject these ones_ but this does **not** mean _always use these options when serialising_ so this is expected. – stuartd Apr 17 '23 at 00:24
  • 1
    What you’re trying to do is change the default options, which isn’t possible (and is [‘not planned’](https://github.com/dotnet/runtime/issues/31094)) – stuartd Apr 17 '23 at 00:33
  • there are hacky ways using reflection - https://stackoverflow.com/questions/58331479/how-to-globally-set-default-options-for-system-text-json-jsonserializer - but I would be cautious about using those. – stuartd Apr 17 '23 at 00:34
  • 1
    Server side does have `services.AddControllers().AddJsonOptions(...)`. That made me think `Configure(...)` would do the same for my client side code ;-) So the standard approach would be to `Configure(...)`, then inject them everywhere and use the appropriate overload of `JsonSerializer.Serialize(...)` with the injected options, right? Again, thank you! – Jens Mander Apr 17 '23 at 00:45

0 Answers0