Json.NET文档说您过去JsonIgnore不对类中的某些属性进行序列化:
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?
JsonConvert.SerializeObject
制作自定义合同解析器:
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);