Skip to content

JsonElement properties do not support JsonIgnoreCondition.WhenWritingNull #114102

Open
@eiriktsarpalis

Description

@eiriktsarpalis

Consider the following console application:

Console.WriteLine(JsonSerializer.Serialize(new MyPoco()));

public class MyPoco
{
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public JsonElement Foo { get; set; } = JsonDocument.Parse("null").RootElement;
}

Even though JsonElement is capable of representing null instances, the serializer will reject this configuration with the message

System.InvalidOperationException: 'The ignore condition 'JsonIgnoreCondition.WhenWritingNull' is not valid on value-type member 'Foo' on type 'MyPoco'. Consider using 'JsonIgnoreCondition.WhenWritingDefault'.'

Even though WhenWritingDefault works, default(JsonElement) is an invalid value that is unfortunately different than the JsonElement null representation. This means that there currently is no mechanism for naturally serializing optional JsonElement properties and you're forced to use JsonElement? instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions