c# - NewtonSoft 在运行时添加 JSONIGNORE

标签 c# attributes json.net

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

相关文章:

C# 将 JSON 反序列化为各种类型

c# - 如何在 C# 中创建键/值对数组?

c# - JSON反序列化对象不起作用

c# - 使用 Owin.Testing 时获取远程 ip

c# - 通过匹配其属性来填充类

core-data - 核心数据删除对象: sets attributes to nil

c# - "unhandy"字典的JSON反序列化

c# - 我们如何在将文件上传到 asp.net 之前检查文件类型?

c# - 未找到 EmguCV DLL 异常 - 无法找到 cvextern?

wordpress - WooCommerce:日期作为属性术语