我怎么能告诉Json.NET忽略第三方对象的属性? [英] How can I tell Json.NET to ignore properties in a 3rd-party object?
本文介绍了我怎么能告诉Json.NET忽略第三方对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的Json.NET文档说,你用 JsonIgnore
来在你的类不序列的某些属性:
The Json.NET documentation says you use JsonIgnore
to not serialize certain properties in your classes:
public class Account
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
[JsonIgnore]
public string PasswordHash { get; set; }
}
我怎样才能让Json.NET序列化3rd-时忽略特定属性与 JsonConvert.SerializeObject
?
推荐答案
请自定义合同解析
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(Account) && property.PropertyName == "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);
这篇关于我怎么能告诉Json.NET忽略第三方对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文