How can I tell Json.NET to ignore properties in a 3rd-party object?

Luckily, Newtonsoft.Json has an override on the JsonConvert.SerializeObject() method that allows us to provide a type, so that the resulting JSON doesn't contain properties that don't exist in that type. So, to eliminate properties, you can make a safe copy of your Account class with all the sensitive properties removed, and give it a different name:

public class AccountJSON
{
    public string FullName { get; set; }
    public string EmailAddress { get; set; }
}

Provide its type when serializing:

var TheAccount = DBContext.Accounts.Find(1);
var TheJSON = Newtonsoft.Json.JsonConvert.SerializeObject(TheAccount, typeof(AccountJSON));

Note: This may only work on the first level deep when the serializer travels through the object. If the Account object has lazy loading properties that reference even more Account objects, they may not use the "safe" type that you originally provided.


Make a custom contract resolver:

public class ShouldSerializeContractResolver : DefaultContractResolver
{
    public static ShouldSerializeContractResolver Instance { get; } = new ShouldSerializeContractResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);        
        if (typeof(Account).IsAssignableFrom(member.DeclaringType) && member.Name == nameof(Account.PasswordHash))
        {
            property.Ignored = true;
        }
        return property;
    }
}

How I test it:

        var account = new Account
        {
            PasswordHash = "XXAABB"
        };
        var settings = new JsonSerializerSettings
        {
            ContractResolver = ShouldSerializeContractResolver.Instance
        };
        var json = JsonConvert.SerializeObject(account, settings);
        Console.WriteLine(json);

Tags:

C#

Json

Json.Net