Skip to content

JsonIgnore not working properly for generator #116003

Closed
@WeihanLi

Description

@WeihanLi

Description

The new ignore condition WhenWriting not working as expected when serialize using the source generator
#66490

Reproduction Steps

var p1 = new Person
{
    Id = 1,
    Name = "Jane",
    Description = "Jane J"
};

Console.WriteLine("JsonIgnoreWhenReadWriteSample with generator");

var jsonP1 = JsonSerializer.Serialize(p1, CustomJsonSerializerContext.Default.Person);
Console.WriteLine(jsonP1);

sealed class Person
{
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWriting)]
    public int Id { get; set; }
    
    public required string Name { get; set; }

    
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenReading)]
    public string? Description { get; set; }

    public override string ToString()
    {
        return $"{Id}-{Name}";
    }
}

[JsonSerializable(typeof(Person))]
internal partial class CustomJsonSerializerContext : JsonSerializerContext
{
}

Expected behavior

The id should be ignored when writing, expected output:

{"Name":"Jane","Description":"Jane J"}

Actual behavior

Actual output:

{"Id":1,"Name":"Jane","Description":"Jane J"}

Regression?

No response

Known Workarounds

using without generator is expected

Configuration

.NET 10 Preview 4

Other information

Maybe something missed for generator serializing, create this in case I forgot this

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions