CodexBloom - Programming Q&A Platform

C# - Custom JSON Serialization Issue with System.Text.Json and DateTime Formatting

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-22
c# json serialization datetime dotnet-6 C#

I'm integrating two systems and I'm working on a project and hit a roadblock... I tried several approaches but none seem to work. I'm facing an issue with custom JSON serialization using `System.Text.Json` in my .NET 6 application. I have a model with a `DateTime` property that I want to format in a specific way (i.e., `yyyy-MM-dd`). However, despite my attempts to configure the serializer options, the output JSON still shows the default `DateTime` format. Here's the relevant model and the code snippet I'm using for serialization: ```csharp public class Event { public string Name { get; set; } public DateTime EventDate { get; set; } } var myEvent = new Event { Name = "Sample Event", EventDate = DateTime.Now }; var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() }, WriteIndented = true, }; string json = JsonSerializer.Serialize(myEvent, options); Console.WriteLine(json); ``` I've tried adding a custom `JsonConverter` for the `DateTime` property, but it doesn't seem to be recognized. Here's the converter I attempted to implement: ```csharp public class CustomDateTimeConverter : JsonConverter<DateTime> { public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString("yyyy-MM-dd")); } public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return DateTime.Parse(reader.GetString()); } } ``` To apply this converter, I modified my serialization options: ```csharp var options = new JsonSerializerOptions { Converters = { new CustomDateTimeConverter() }, WriteIndented = true, }; ``` However, when I run the code, the `EventDate` still outputs in the default format, like this: `"EventDate":"2023-10-01T14:30:00Z"`. What am I missing? Is there a specific way I need to configure the converter to ensure it gets applied correctly? This is part of a larger application I'm building. Thanks in advance! The project is a application built with C#. Has anyone dealt with something similar? The project is a web app built with C#. I'm open to any suggestions.