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:

  • Open up metadata infrastructure of System.Text.Json #34456
  • Equivalent of DefaultContractResolver.CreateProperties override in System.Text.Json #60518
  • Equivalent of DefaultContractResolver in System.Text.Json #31257

Please try this:
I wrote this as an extension to System.Text.Json to offer missing features:

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())

    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();

Register the new object mapping convention for the class:

    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 = ""
string json = JsonSerializer.Serialize(employee, options);
// {"Id":12,"FirstName":"John","Email":""};

Leave a Comment