我想使用 NewtonSoft JSON 序列化一个列表,我需要在序列化时忽略其中一个属性,我得到了以下代码
public class Car
{
// included in JSON
public string Model { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
但是我在我的应用程序中的许多地方都使用了这个特定类 Car,我只想在一个地方排除该选项。
我可以在我需要的特定位置动态添加 [JsonIgnore] 吗?我该怎么做?
最佳答案
无需执行其他答案中解释的复杂内容。
NewtonSoft JSON 有一个内置功能:
public bool ShouldSerializeINSERT_YOUR_PROPERTY_NAME_HERE()
{
if(someCondition){
return true;
}else{
return false;
}
}
它被称为“条件属性序列化”和文档 can be found here .
警告:首先,删除 {get;set;}
属性上方的 [JsonIgnore]
很重要。否则它将覆盖 ShouldSerializeXYZ
行为。
关于c# - NewtonSoft 在运行时添加 JSONIGNORE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25157511/