[英]How to ignore properties when serializing to json that does not involve attributes
[英]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 時不會對其進行序列化。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.