Unexpected JSON Serialization Behavior in ASP.NET Core with Custom Objects
Quick question that's been bugging me - I keep running into I've hit a wall trying to I'm sure I'm missing something obvious here, but I've been struggling with this for a few days now and could really use some help..... I'm encountering a perplexing issue while trying to serialize a custom object to JSON in my ASP.NET Core 6.0 application. I have a class with a few properties, some of which are nullable, and I expected the JSON output to include only the non-null properties. However, when I serialize the object using `System.Text.Json.JsonSerializer`, it seems to be including the nullable properties with `null` values. Here is the class definition: ```csharp public class User { public string Name { get; set; } public int Age { get; set; } public string? Email { get; set; } public string? Address { get; set; } } ``` When I created an instance of this class without setting the `Email` and `Address`, it looks like this: ```csharp var user = new User { Name = "John Doe", Age = 30 }; ``` Upon serialization, I run the following code: ```csharp var jsonString = JsonSerializer.Serialize(user); Console.WriteLine(jsonString); ``` But the output is: ```json {"Name":"John Doe","Age":30,"Email":null,"Address":null} ``` I expected the output to exclude the `Email` and `Address` properties altogether. I've looked into setting options for serialization, but nothing seems to work. I've tried adding `JsonSerializerOptions` like this: ```csharp var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; var jsonString = JsonSerializer.Serialize(user, options); ``` ``` However, the null properties still appear in the output. Is there something I'm missing? Am I using the serialization settings incorrectly? Any guidance on how to achieve the desired JSON output would be greatly appreciated! For context: I'm using Csharp on Windows. I'm on Ubuntu 20.04 using the latest version of Csharp. Cheers for any assistance! This is part of a larger REST API I'm building. Any ideas how to fix this? My development environment is Windows 10. Any advice would be much appreciated. Thanks for any help you can provide!