CodexBloom - Programming Q&A Platform

advanced patterns When Using C# 10 Record Types with Custom JSON Serialization Settings

👀 Views: 33 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
c# json serialization record-types nullable-types C#

I've spent hours debugging this and I'm having trouble with custom JSON serialization when using C# 10 record types. I defined a record for a user profile, which includes a nullable `DateTime` property for the `LastLogin` timestamp. However, when I serialize this record using `System.Text.Json`, the `LastLogin` property is being serialized as `null` even when it's set to a valid `DateTime` value. Here's the record definition: ```csharp public record UserProfile(string Username, string Email, DateTime? LastLogin); ``` And when I serialize it: ```csharp var profile = new UserProfile("user123", "user@example.com", DateTime.Now); var options = new JsonSerializerOptions { WriteIndented = true }; string json = JsonSerializer.Serialize(profile, options); ``` I expect the output to include the `LastLogin` timestamp, but it looks like this: ```json { "Username": "user123", "Email": "user@example.com", "LastLogin": null } ``` I have confirmed that the `LastLogin` property is not `null` before serialization. I've also tried to set `JsonSerializerOptions.PropertyNamingPolicy` to `null`, but that didn't change the result. Is there something I'm missing with how `System.Text.Json` handles record types, especially with nullable properties? I would appreciate any insights or suggestions on what might be going wrong. This is my first time working with C# stable. Any examples would be super helpful.