如何防止使用系统对只读集合属性进行序列化,Text.Json.JsonSerializer?

kxe2p93d  于 2023-05-02  发布在  其他
关注(0)|答案(2)|浏览(75)

创建具有只读集合属性的类。使用System.Text.Json.JsonSerializer序列化,并带有指定IgnoreReadOnlyProperties = true的选项。只读集合属性仍在序列化,而其他只读属性则未序列化。反序列化后,所有只读属性都将按预期被忽略。
为什么在序列化时对集合进行不同的处理?
我可以阻止序列化没有[JsonIgnore]属性的只读集合属性吗?
序列化方法的选择不在我的控制范围内,所以我希望在代码中没有序列化特定的属性。
使用以下测试类:

public class TestJSONClass
{
   public int ReadOnlyInt { get; } = 1;
   public IEnumerable<int> ReadOnlyCollection { get; } = new int[2];

   public int ReadWriteInt { get; set; } = 3;
   public IEnumerable<int> ReadWriteCollection { get; set; } = new int[4];
}

然后序列化人:

JsonSerializerOptions options = new JsonSerializerOptions() { WriteIndented = true, IgnoreReadOnlyProperties = true };
JsonSerializer.Serialize(new TestJSONClass(), options);

我得到下面的输出。正如预期的那样,ReadOnlyInt没有序列化。但是,ReadOnlyCollection * 是 * 序列化的。

{
  "ReadOnlyCollection": [
    0,
    0
  ],
  "ReadWriteInt": 3,
  "ReadWriteCollection": [
    0,
    0,
    0,
    0
  ]
}

我的目标是获得以下内容:

{
  "ReadWriteInt": 3,
  "ReadWriteCollection": [
    0,
    0,
    0,
    0
  ]
}
7hiiyaii

7hiiyaii1#

IgnoreReadOnlyProperties/Fields = true不适用于集合。
资料来源: www.example.com
原因是确保可以应用规则CA 2227,并且仍然使用JsonSerializer来反序列化集合https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2227?view=vs-2019
我最好的猜测是使用[JsonIgnore]。如果你不能或不想使用它,你可以编写自己的转换器/规则。但我认为这一点也不容易。

dzjeubhm

dzjeubhm2#

避免属性序列化的方法之一是将属性标记为内部属性,这样它就不会被序列化。
所以在你的情况下,改变你的台词

public IEnumerable<int> ReadOnlyCollection { get; } = new int[2];

internal IEnumerable<int> ReadOnlyCollection { get; } = new int[2];

您将得到以下结果:

{
  "ReadWriteInt": 3,
  "ReadWriteCollection": [
    0,
    0,
    0,
    0
  ]
}

相关问题