简体   繁体   English

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

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

The Json.NET documentation says you use JsonIgnore to not serialize certain properties in your classes: Json.NET文档说您使用JsonIgnore来不序列化类中的某些属性:

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

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

How can I make Json.NET ignore specific properties when serializing a 3rd-party object with JsonConvert.SerializeObject ? 使用JsonConvert.SerializeObject序列化第三方对象时,如何使Json.NET忽略特定属性?

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

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. 幸运的是, Newtonsoft.JsonJsonConvert.SerializeObject()方法上有一个重写,该重写使我们能够提供一种类型,以便生成的JSON不包含该类型中不存在的属性。 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: 因此,要消除属性,可以删除所有敏感属性的情况下对Account类进行安全复制,并为其指定其他名称:

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. 如果Account对象具有引用甚至更多Account对象的延迟加载属性,则它们可能不使用您最初提供的“安全”类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM