You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fast-path source generator not honoring JsonIgnoreCondition.WhenWritingNull for Nullable<T> properties. #96404
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);
}
}
}
changed the title [-]Inconsistent behavior with JsonIgnoreCondition.WhenWritingNull in .NET 8[/-][+]Fast-path source generator not honoring `JsonIgnoreCondition.WhenWritingNull` for `Nullable<T>` properties.[/+]on Jan 8, 2024
I can confirm this is a bug of the fast-path generator which doesn't apply the WhenWritingNull condition for properties of type Nullable<T>. This appears to be a regression from .NET 7 and we should try to service it. As a temporary workaround you can disable fast-path like so:
Activity
[-]Inconsistent behavior with JsonIgnoreCondition.WhenWritingNull in .NET 8[/-][+]Fast-path source generator not honoring `JsonIgnoreCondition.WhenWritingNull` for `Nullable<T>` properties.[/+]eiriktsarpalis commentedon Jan 8, 2024
I can confirm this is a bug of the fast-path generator which doesn't apply the
WhenWritingNullcondition for properties of typeNullable<T>. This appears to be a regression from .NET 7 and we should try to service it. As a temporary workaround you can disable fast-path like so: