簡體   English   中英

序列化到 json 時如何忽略空列表?

[英]How to ignore empty list when serializing to json?

我試圖弄清楚如何序列化為 json object 並跳過序列化值為空列表的屬性。 我沒有使用 Newtonsoft json

using System.Text.Json;
using System.Text.Json.Serialization;
using AutoMapper;

我有一個帶有屬性的 object。

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

當我嘗試使用以下序列化此 object 時

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

var json = JsonSerializer.Serialize(report, optionsJson);

它仍然給我一個空數組:

"extension": [],

有沒有辦法阻止它序列化這些空列表? 我希望看到extension消失了。 它根本不應該在那里。 我需要這樣做,因為如果我發送以下內容,網關將以錯誤響應:

"extension": null,

序列化時,它不能是 object 的一部分。

網關錯誤

我不想要這些空列表的原因是我發送給對象的第三方網關到空列表

"severity": "error", "code": "processing", "diagnostics": "Array cannot be empty - property should not present if it has no values", "location": [ "Bundle.entry[2 ].resource.extension", "第 96 行,第 23 欄" ]

我試圖避免對此進行某種討厭的字符串替換。

您可以添加一個在處理此問題的序列化期間使用的虛擬屬性。

  • 添加具有相同簽名的新屬性,但使用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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM