NewtonSoft 在运行时添加 JSONIGNORE [英] NewtonSoft add JSONIGNORE at runTime
问题描述
我想使用 NewtonSoft JSON 序列化一个列表,我需要在序列化时忽略其中一个属性,我得到了以下代码
Am looking to Serialize a list using NewtonSoft JSON and i need to ignore one of the property while Serializing and i got the below code
public class Car
{
// included in JSON
public string Model { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
但是我在我的应用程序的很多地方都使用了这个特定的类 Car,我只想在一个地方排除这个选项.
But am using this Specific class Car in many places in my application and i want to Exclude the option only in one place.
我可以在需要的特定位置动态添加 [JsonIgnore] 吗?我该怎么做?
Can i dynamically add [JsonIgnore] in the Specific Place where i need ? How do i do that ?
推荐答案
无需做其他答案中解释的复杂内容.
No need to do the complicated stuff explained in the other answer.
NewtonSoft JSON 有一个内置功能:
NewtonSoft JSON has a built-in feature for that:
public bool ShouldSerializeINSERT_YOUR_PROPERTY_NAME_HERE()
{
if(someCondition){
return true;
}else{
return false;
}
}
它被称为条件属性序列化",文档可以在这里找到.
It is called "conditional property serialization" and the documentation can be found here.
警告:首先,去掉 {get;set;}
属性上方的 [JsonIgnore]
很重要.否则它将覆盖 ShouldSerializeXYZ
行为.
Warning: first of all, it is important to get rid of [JsonIgnore]
above your {get;set;}
property. Otherwise it will overwrite the ShouldSerializeXYZ
behavior.
这篇关于NewtonSoft 在运行时添加 JSONIGNORE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!