【问题标题】:System.Json - custom rules for property serialization skippingSystem.Json - 属性序列化跳过的自定义规则
【发布时间】:2021-12-12 12:55:03
【问题描述】:

我正在尝试从 Newtonsoft.Json 迁移到 System.Text.Json 但是,由于我使用的是 DefaultContractResolver,所以我遇到了一个问题。 我的“自定义”行为有这些属性序列化规则:

  1. 如果用 ReadOnly 属性标记,则跳过属性序列化
  2. 在 null 的情况下跳过属性序列化(支持)
  3. 跳过将序列化为空对象的属性序列化

例子:

class Car
{
  [ReadOnly]
  public string Id { get; set; }

  public string Name { get; set; }

  public Person Owner { get; set; }
}

class Person
{
  [ReadOnly]
  public string Id { get; set; }

  public string Name { get; set; }
}

现在,想象一下,如果没有适用的规则,我们就有了这些数据。

{
   "Id":"1234",
   "Name":"Skoda",
   "Owner":{
      "Id":"abcd",
      "Name":null
   }
}

现在,如果我序列化对象,我希望得到它。

{
   "Name":"Skoda"
}

【问题讨论】:

标签: c# json .net serialization system.text.json


【解决方案1】:

为了忽略单个属性,您需要使用[JsonIgnore] 属性以及以下条件之一:

  • Always;
  • Never;
  • WhenWritingDefault;
  • WhenWritingNull

您还可以通过JsonSerializerOptions 类型定义默认忽略条件。

如果需要额外的行为,你应该编写一个自定义转换器。

例子:

class Person
{
  [JsonIgnore(Condition = JsonIgnoreCondition.Always)]
  public string Id { get; set; }

  [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  public string Name { get; set; }
}

更多信息:

How to ignore properties with System.Text.Json

How to write custom converters for JSON serialization (marshalling) in .NET

【讨论】:

  • 谢谢,但 [JsonIgnore] 无法解决我的问题。我需要它只忽略序列化,而不是反序列化。我想添加自定义转换器,但我需要为任何类型添加自定义转换器。基本上,对于任何类型,检查它是否为空(将序列化为“{}”)或具有特定属性,如果是,则跳过它,如果不是,应用标准转换器。
猜你喜欢
  • 2015-07-27
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 2014-07-24
  • 1970-01-01
  • 2017-04-06
相关资源
最近更新 更多