Skip to content

Fast-path source generator not honoring JsonIgnoreCondition.WhenWritingNull for Nullable<T> properties. #96404

@john10e

Description

@john10e

Shouldn't these two serialization methods output the same format in NET 8? It does in NET 6/7. If not, is there a way to use source generation and ignore writing null int? values to reduce string/file size?

using System.Text.Json;
using System.Text.Json.Serialization;

namespace TestJsonSerialization
{
    public class Forecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public string? Summary { get; set; }

        public int? SomeCounter { get; set; }
    };

    [JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
    [JsonSerializable(typeof(Forecast))]
    public partial class ForecastSerializationContext: JsonSerializerContext
    { }


    [TestClass]
    public class TestIgnoreNullPolicies
    {
        [TestMethod]
        public void TestIgnoreNull()
        {
            var f = new Forecast { Date = new DateTime(2021,12,01), TemperatureC = 30, Summary = null, SomeCounter = null };
            var sourceGenResult = JsonSerializer.Serialize(f, ForecastSerializationContext.Default.Forecast); //{"Date":"2021-12-01T00:00:00","TemperatureC":30,"SomeCounter":null}


            JsonSerializerOptions options = new()
            {
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
            };
            var reflectionResult = JsonSerializer.Serialize(f, options);  //{"Date":"2021-12-01T00:00:00","TemperatureC":30}

            Assert.AreEqual(sourceGenResult, reflectionResult, true);  
        }
    }
}

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions