Serialize to JSON only some records from a dictionary in a complex type

You can implement a custom value provider (using IValueProvider) to handle this. The value provider can take in the list of sensitive property names, and transform the dictionary to exclude the sensitive properties:

public class PartialSensitiveInformationValueProvider : IValueProvider
{
    private readonly HashSet<string> _propertyNamesToIgnore;

    public PartialSensitiveInformationValueProvider(HashSet<string> propertyNamesToIgnore)
    {
        _propertyNamesToIgnore = propertyNamesToIgnore;
    }

    public object GetValue(object target)
    {
        return ((Information)target).PartialSensitiveInformation
            .Where(x => !_propertyNamesToIgnore.Contains(x.Key))
            .ToDictionary(k => k.Key, v => v.Value);
    }

    public void SetValue(object target, object value)
    {
        throw new NotImplementedException();
    }
}

You can then use this value provider in the contract resolver:

public class IgnorePropertiesContractResolver : DefaultContractResolver
{
    private readonly HashSet<string> propertyNamesToIgnore;

    public IgnorePropertiesContractResolver(HashSet<string> propertyNamesToIgnore)
    {
        this.propertyNamesToIgnore = propertyNamesToIgnore;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty jsonProperty = base.CreateProperty(member, memberSerialization);
        if (this.propertyNamesToIgnore.Contains(jsonProperty.PropertyName))
        {
            jsonProperty.ShouldSerialize = x => false;
        }

        if (jsonProperty.PropertyName == nameof(Information.PartialSensitiveInformation))
        {
            jsonProperty.ValueProvider = new PartialSensitiveInformationValueProvider(this.propertyNamesToIgnore);
        }

        return jsonProperty;
    }
}

Using the example you have (including “secret_data” in the propertyNamesToIgnore), the results are now:

{"NotSensitiveInformation":"not sensitive data","PartialSensitiveInformation":{"not_secret_data":"not secret data"}}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top