假設我實體化了一個以下物件。
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
[JsonExtensionData]
public IReadOnlyDictionary<string, string> AdditionalProperties { get; set; }
}
Parent parent = new() { Id = 1, Name = "Parent", AdditionalProperties = new Dictionary<string, string>() { { "Property", "SomeProperty" } } };
這將被轉換為以下 JSON 結構:
parent {
id: 1,
name: "parent",
additionalProperties: {
property: "someProperty
}
}
相反,我想將其展平并將以下 json 物件回傳給用戶。
parent {
id: 1,
name: "parent",
property: "someProperty"
}
我可以使用動態或擴展物件處理其他屬性,但我不希望這樣,我需要它盡可能強型別,所以我決定將動態屬性存盤在字典中。
uj5u.com熱心網友回復:
不幸的是,您沒有告訴我們您使用的是哪個 JSON 序列化程式,所以我測驗了 Microsoft 和 Newtonsoft。如果您的屬性是 type ,兩者都會拋出錯誤IReadOnlyDictionary<string, string>,但是如果您將其更改為Dictionary<string, object>它
來源
:教程
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/445013.html
