Question

Can I dynamically ignore a property from a sealed class using System.Text.Json.JsonSerializer?

Example Code

Example class from another library:

public sealed class FrozenClass
{
    // [JsonIgnore] <- cannot apply because I don't own this class
    public int InternalId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Default Serialization:

var person = new FrozenClass() { InternalId = 3, FirstName = "Dorothy", LastName = "Vaughan" };
var jsonString = System.Text.Json.JsonSerializer.Serialize(person);

Actual Outcome:

{ "InternalId": 3, "FirstName": "Dorothy", "LastName": "Vaughan" }

Expected Outcome:

{ "FirstName": "Dorothy", "LastName": "Vaughan" }

Alternatives that don't work

There are two other questions on how to add JsonIgnore at RunTime & add dynamic property name for serialization, but both are targeted at Newtonsoft's Json.NET - and often reference this extension method

There are several ways to modify the way a class is serialized with the native JsonSerializer, but all seem to rely on modifying the underlying class:

However, in my case, the class is from another library and cannot be extended

Workarounds

A possible workaround is to create another exportable class and setup a mapper between them

public class MyFrozenClass
{
    public MyFrozenClass(FrozenClass frozen)
    {
        this.FirstName = frozen.FirstName;
        this.LastName = frozen.LastName;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
var jsonString = System.Text.Json.JsonSerializer.Serialize(new MyFrozenClass(person));