System.Text.Json API is there something like IContractResolver

后端 未结 1 446
慢半拍i
慢半拍i 2020-12-12 02:51

In the new System.Text.Json; namespace is there something like IContractResolver i am trying to migrate my project away from Newtonsoft.

This is one of the classes i

相关标签:
1条回答
  • 2020-12-12 02:54

    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 Issue

    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 = "john.doe@acme.com"
    };
            
    string json = JsonSerializer.Serialize(employee, options);
    // {"Id":12,"FirstName":"John","Email":"john.doe@acme.com"};
    
    0 讨论(0)
提交回复
热议问题