我從 Attribute 型別創建了一個類
public class DemoAttribute : Attribute {
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Label { get; private set; }
public DemoAttribute(string label = null) {
this.Label = label;
}
}
當我嘗試使用 System.Text.Json 對其進行序列化時
var demo = new DemoAttribute("test");
var json = JsonSerializer.Serialize(demo);
我收到一個 InvalidOperationException:
只能在 Type.IsGenericParameter 為 true 的型別上呼叫方法。
我可以在不首先將屬性復制到具有相同屬性的“常規”類的情況下序列化屬性嗎?
編輯/添加 我正在使用一個更廣泛的屬性和屬性上的元資料,比如(在前端)標簽、幫助文本、圖示、驗證規則、占位符等是什么。通過反射,我得到了屬性的屬性我想序列化它(屬性的屬性),以便我可以將它發送到前端。
uj5u.com熱心網友回復:
Attribute具有TypeId默認包含屬性型別的屬性(請參閱檔案中的備注),在使用System.Text.Json. 您可以覆寫此屬性并忽略它:
public class DemoAttribute : Attribute
{
[JsonIgnore]
public override object TypeId { get; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Label { get; private set; }
public DemoAttribute(string label = null)
{
this.Label = label;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317076.html
上一篇:BackgroundService中的BlockingCollection<T>導致CPU使用率高
下一篇:For回圈重構?
