Rex*_*x M 56 c# serialization custom-attributes json.net
我需要能够控制如何/是否序列化类上的某些属性.最简单的情况是[ScriptIgnore].但是,我只希望这些属性能够适用于我正在处理的这个特定的序列化情况 - 如果应用程序中的下游其他模块也想要序列化这些对象,则这些属性都不应该妨碍.
所以我的想法是在属性MyAttribute上使用自定义属性,并使用知道查找该属性的钩子初始化JsonSerializer的特定实例.
乍一看,我没有看到JSON.NET中任何可用的钩子点都会为PropertyInfo当前属性提供这样的检查 - 只有属性的值.我错过了什么吗?或者更好的方法来解决这个问题?
drz*_*aus 69
这是一个基于接受的答案的通用可重用"忽略属性"解析器:
/// <summary>
/// Special JsonConvert resolver that allows you to ignore properties. See https://stackoverflow.com/a/13588192/1037948
/// </summary>
public class IgnorableSerializerContractResolver : DefaultContractResolver {
protected readonly Dictionary<Type, HashSet<string>> Ignores;
public IgnorableSerializerContractResolver() {
this.Ignores = new Dictionary<Type, HashSet<string>>();
}
/// <summary>
/// Explicitly ignore the given property(s) for the given type
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName">one or more properties to ignore. Leave empty to ignore the type entirely.</param>
public void Ignore(Type type, params string[] propertyName) {
// start bucket if DNE
if (!this.Ignores.ContainsKey(type)) this.Ignores[type] = new HashSet<string>();
foreach (var prop in propertyName) {
this.Ignores[type].Add(prop);
}
}
/// <summary>
/// Is the given property for the given type ignored?
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public bool IsIgnored(Type type, string propertyName) {
if (!this.Ignores.ContainsKey(type)) return false;
// if no properties provided, ignore the type entirely
if (this.Ignores[type].Count == 0) return true;
return this.Ignores[type].Contains(propertyName);
}
/// <summary>
/// The decision logic goes here
/// </summary>
/// <param name="member"></param>
/// <param name="memberSerialization"></param>
/// <returns></returns>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (this.IsIgnored(property.DeclaringType, property.PropertyName)
// need to check basetype as well for EF -- @per comment by user576838
|| this.IsIgnored(property.DeclaringType.BaseType, property.PropertyName)) {
property.ShouldSerialize = instance => { return false; };
}
return property;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var jsonResolver = new IgnorableSerializerContractResolver();
// ignore single property
jsonResolver.Ignore(typeof(Company), "WebSites");
// ignore single datatype
jsonResolver.Ignore(typeof(System.Data.Objects.DataClasses.EntityObject));
var jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver };
Run Code Online (Sandbox Code Playgroud)
小智 65
使用该JsonIgnore属性.
例如,要排除Id:
public class Person {
[JsonIgnore]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Ran*_*pho 44
你有几个选择.我建议您在阅读下面的内容之前阅读有关该主题的Json.Net文档文章.
本文介绍了两种方法:
bool根据Json.Net将遵循的命名约定返回一个值,以确定是否序列化该属性.在这两者中,我赞成后者.完全跳过属性 - 仅使用它们来忽略所有形式的序列化中的属性.相反,创建一个忽略相关属性的自定义合约解析程序,并且只在您想要忽略该属性时才使用合同解析程序,让该类的其他用户可以自由地序列化该属性,或者不要随意使用.
编辑为了避免链接腐烂,我将从文章中发布有问题的代码
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(Employee) &&
property.PropertyName == "Manager" )
{
property.ShouldSerialize = instance =>
{
// replace this logic with your own, probably just
// return false;
Employee e = (Employee)instance;
return e.Manager != e;
};
}
return property;
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*uts 27
这是一个基于drzaus优秀序列化器合约的方法,它使用lambda表达式.只需将其添加到同一个班级.毕竟,谁不喜欢编译器来检查它们?
public IgnorableSerializerContractResolver Ignore<TModel>(Expression<Func<TModel, object>> selector)
{
MemberExpression body = selector.Body as MemberExpression;
if (body == null)
{
UnaryExpression ubody = (UnaryExpression)selector.Body;
body = ubody.Operand as MemberExpression;
if (body == null)
{
throw new ArgumentException("Could not get property name", "selector");
}
}
string propertyName = body.Member.Name;
this.Ignore(typeof (TModel), propertyName);
return this;
}
Run Code Online (Sandbox Code Playgroud)
您现在可以轻松且流畅地忽略属性:
contract.Ignore<Node>(node => node.NextNode)
.Ignore<Node>(node => node.AvailableNodes);
Run Code Online (Sandbox Code Playgroud)