序列化为json时如何忽略空列表?

DaI*_*mTo 9 c# json system.text.json .net-6.0

我试图弄清楚如何序列化为 json 对象并跳过序列化值为空列表的属性。 我没有使用 Newtonsoft json

using System.Text.Json;
using System.Text.Json.Serialization;
using AutoMapper;
Run Code Online (Sandbox Code Playgroud)

我有一个带有属性的对象。

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonPropertyName("extension")]
public List<Extension> Extension { get; set; }
Run Code Online (Sandbox Code Playgroud)

当我尝试使用以下命令序列化该对象时

var optionsJson =   new JsonSerializerOptions
    {
    WriteIndented = true,
    IgnoreNullValues = true,
    PropertyNameCaseInsensitive = true,
    };

var json = JsonSerializer.Serialize(report, optionsJson);
Run Code Online (Sandbox Code Playgroud)

它仍然给我一个空数组:

"extension": [],
Run Code Online (Sandbox Code Playgroud)

有没有办法阻止它序列化这些空列表?我愿意看到extension消失。它根本不应该存在。我需要这样做,因为如果我发送以下内容,网关将响应错误:

"extension": null,
Run Code Online (Sandbox Code Playgroud)

序列化时它不能是对象的一部分。

网关错误

我不想要这些空列表的原因是我发送到对象到空列表的第三方网关

"severity": "error", "code": "processing", "diagnostics": "数组不能为空 - 如果属性没有值,则不应存在", "location": [ "Bundle.entry[2 ].resource.extension", "第 96 行,第 23 栏"]

我试图避免对此进行某种令人讨厌的字符串替换。

ang*_*son 10

您可以添加一个在序列化过程中使用的虚拟属性来处理此问题。

  • 添加具有相同签名的新属性,但对其进行标记JsonPropertyNameAttribute以确保使用正确的名称对其进行序列化,并且还使用 进行标记,JsonIgnoreAttribute以便在返回 null 时不会对其进行序列化。
  • 您无条件地用 JsonIgnore 标记的原始属性,这样它本身就永远不会被序列化
  • 当实际属性包含空列表时,此虚拟属性将返回null(因此被忽略),否则它将返回该(非空)列表
  • 写入虚拟属性只是写入实际属性

像这样的东西:

[JsonIgnore]
public List<Extension> Extensions { get; set; } = new();

[JsonPropertyName("extension")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
 public List<Extension> SerializationExtensions
    {
        get => Extensions?.Count > 0 ? Extensions : null;
        set => Extensions = value ?? new();
    }
Run Code Online (Sandbox Code Playgroud)