一尘不染

如何告诉Json.NET忽略第三方对象中的属性?

json

Json.NET文档说您过去JsonIgnore不对类中的某些属性进行序列化:

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

    [JsonIgnore]
    public string PasswordHash { get; set; }
}

在使用序列化第3方对象时,如何使Json.NET忽略特定属性JsonConvert.SerializeObject


阅读 180

收藏
2020-07-27

共1个答案

一尘不染

制作自定义合同解析器:

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;
    }
}

我如何测试它:

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