NewtonSoft在运行时添加JSONIGNORE [英] NewtonSoft add JSONIGNORE at runTime

查看:400
本文介绍了NewtonSoft在运行时添加JSONIGNORE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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;
    }
}

这称为条件属性序列化",可以在此处找到文档 /a>.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆