System.Text.Json API is there something like IContractResolver

The equivalent types in System.Text.Json — JsonClassInfo and JsonPropertyInfo — are internal. There is an open enhancement
Equivalent of DefaultContractResolver in System.Text.Json #31257
asking for a public equivalent. – dbc Nov 25 at 19:11

Github issues:

Please try this:
I wrote this as an extension to System.Text.Json to offer missing features: https://github.com/dahomey-technologies/Dahomey.Json.

You will find support for programmatic object mapping.

Define your own implementation of IObjectMappingConvention:

public class SelectiveSerializer : IObjectMappingConvention
{
    private readonly IObjectMappingConvention defaultObjectMappingConvention = new DefaultObjectMappingConvention();
    private readonly string[] fields;

    public SelectiveSerializer(string fields)
    {
        var fieldColl = fields.Split(',');
        this.fields = fieldColl
            .Select(f => f.ToLower().Trim())
            .ToArray();
    }

    public void Apply<T>(JsonSerializerOptions options, ObjectMapping<T> objectMapping) where T : class
    {
        defaultObjectMappingConvention.Apply<T>(options, objectMapping);
        foreach (IMemberMapping memberMapping in objectMapping.MemberMappings)
        {
            if (memberMapping is MemberMapping<T> member)
            {
                member.SetShouldSerializeMethod(o => fields.Contains(member.MemberName.ToLower()));
            }
        }
    }
}

Define your class:

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

Setup json extensions by calling on JsonSerializerOptions the extension method SetupExtensions defined in the namespace Dahomey.Json:

JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();

Register the new object mapping convention for the class:

options.GetObjectMappingConventionRegistry().RegisterConvention(
    typeof(Employee), new SelectiveSerializer("FirstName,Email,Id"));

Then serialize your class with the regular Sytem.Text.Json API:

Employee employee = new Employee
{
    Id = 12,
    FirstName = "John",
    LastName = "Doe",
    Email = "[email protected]"
};
        
string json = JsonSerializer.Serialize(employee, options);
// {"Id":12,"FirstName":"John","Email":"[email protected]"};

Leave a Comment