NewtonSoft在runTime添加JSONIGNORE

我希望使用NewtonSoft JSON序列化一个列表,我需要在序列化时忽略其中一个属性,我得到以下代码

public class Car { // included in JSON public string Model { get; set; } // ignored [JsonIgnore] public DateTime LastModified { get; set; } } 

但我在我的应用程序中的许多地方使用此特定类汽车,我想只在一个地方排除选项。

我可以在我需要的特定位置动态添加[JsonIgnore]吗? 我怎么做 ?

不需要做其他答案中解释的复杂的东西。

NewtonSoft JSON具有内置function:

 public bool ShouldSerializeINSERT_YOUR_PROPERTY_NAME_HERE() { if(someCondition){ return true; }else{ return false; } } 

它被称为“条件属性序列化”,文档可以在这里找到 。

警告:首先,摆脱[JsonIgnore] {get;set;}属性之上的[JsonIgnore]非常重要。 否则它将覆盖ShouldSerializeXYZ行为。

我认为最好使用自定义IContractResolver来实现这一目标:

 public class DynamicContractResolver : DefaultContractResolver { private readonly string _propertyNameToExclude; public DynamicContractResolver(string propertyNameToExclude) { _propertyNameToExclude = propertyNameToExclude; } protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) { IList properties = base.CreateProperties(type, memberSerialization); // only serializer properties that are not named after the specified property. properties = properties.Where(p => string.Compare(p.PropertyName, _propertyNameToExclude, true) != 0).ToList(); return properties; } } 

LINQ可能不正确,我没有机会测试这个。 然后您可以按如下方式使用它:

 string json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("LastModified") }); 

有关更多信息,请参阅文档 。

根据上面的@Underscorepost,我创建了一个要在序列化时排除的属性列表。

 public class DynamicContractResolver : DefaultContractResolver { private readonly string[] props; public DynamicContractResolver(params string[] prop) { this.props = prop; } protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) { IList retval = base.CreateProperties(type, memberSerialization); // retorna todas as propriedades que não estão na lista para ignorar retval = retval.Where(p => !this.props.Contains(p.PropertyName)).ToList(); return retval; } } 

使用:

 string json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("ID", "CreatedAt", "LastModified") }); 

试试这个:

  public static void IgnoreProperty(this T parameter, Expression> propertyLambda) { var parameterType = parameter.GetType(); var propertyName = propertyLambda.GetReturnedPropertyName(); if (propertyName == null) { return; } var jsonPropertyAttribute = parameterType.GetProperty(propertyName).GetCustomAttribute(); jsonPropertyAttribute.DefaultValueHandling = DefaultValueHandling.Ignore; } public static string GetReturnedPropertyName(this Expression> propertyLambda) { var member = propertyLambda.Body as MemberExpression; var memberPropertyInfo = member?.Member as PropertyInfo; return memberPropertyInfo?.Name; } 

所以你可以这样做:

 carObject.IgnoreProperty(so => so.LastModified);