17

My apologies for the silly question, but I don't see a good example of how can I specify a specific format for DateTime in JSON serialization for .net core 6.

The old way, net core 3.

// in the ConfigureServices()
services.AddControllers()
 .AddJsonOptions(options =>
 {
 options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
 });

There is an example on the official website https://learn.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support

JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new DateTimeConverterForCustomStandardFormatR());

"

But how can I wire it up to DI so It is used in the Controller?

D-Shih
46.5k6 gold badges37 silver badges56 bronze badges
asked Apr 29, 2022 at 15:52

1 Answer 1

22

We can try to use builder.Services.Configure<JsonOptions> to set our Serializer setting in DI container from .net core 6

JsonOptions let us configure JSON serialization settings, which might instead AddJsonOptions method.

JsonOptionsmight use same as JsonOptions object from DI in the SourceCode.

using Microsoft.AspNetCore.Http.Json;
builder.Services.Configure<JsonOptions>(options =>
{
 options.SerializerOptions.Converters.Add(new DateTimeConverterForCustomStandardFormatR());
});

I think this change is based on Microsoft wanting to introduce minimal web API with ASP.NET Core in .net 6

Minimal APIs are architected to create HTTP APIs with minimal dependencies. They are ideal for microservices and apps that want to include only the minimum files, features, and dependencies in ASP.NET Core.

answered Apr 29, 2022 at 16:00
2
  • 2
    but how can I add [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] to builder.Services ... ? Commented Jan 26, 2023 at 2:59
  • How can I get a JsonOptions from the constructor of a Razor page model? The runtime can't resolve JsonOptions, neither IOptions<JsonOptions>. Commented Aug 3, 2023 at 10:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.