簡體   English   中英

C# - 在基本 class 列表中序列化派生 class 的所有屬性

[英]C# - Serialize all attributes of derived class in a list of base class

我需要 JsonSerializer.Serialize(...) 一個 class 包含一個基本 class 的列表:

 // ----- Models ----- public class MainClass { [Key] public Guid Id { get; private set; } = Guid.NewGuid(); public List<BaseClass> Properties { get; set; } = new List<BaseClass>(); } public class BaseClass { [Key] public Guid Id { get; private set; } = Guid.NewGuid(); public string Name { get; set; } = string.Empty; } public class GenericDerivedClass<T>: BaseClass { public T? Value { get; set; } } // ----- Implementation ----- var main = new MainClass { Properties = new List<BaseClass> { new GenericDerivedClass<string> { Name = "SoundFile", Value = "Test.wav" }, new GenericDerivedClass<float> { Name = "Volume", Value = 1 }, new GenericDerivedClass<bool> { Name = "Autoplay", Value = false }, new GenericDerivedClass<bool> { Name = "Loop", Value = false }, } }; Console.WriteLine(JsonSerializer.Serialize(main, new JsonSerializerOptions { WriteIndented = true })); // ----- Output (JsonSerializer) ---- [ { "main": [ { "id": "ba348c86-aa86-45ea-8d21-a9beddd4368a", "properties": [ { "id": "a9f432d5-3916-4c1d-b44a-fd4b7d8fcb45", "name": "SoundFile", //"value": "Test.wav" <- I want this line here, but I cannot figure out how. }, { "id": "f585d863-b0d7-49b3-ad5c-0565171e6793", "name": "Volume" }, { "id": "197802f3-17cd-4c1f-90be-7ea643ee5d7d", "name": "Autoplay" }, { "id": "b90e3857-e497-4137-adeb-94b66293d375", "name": "Loop" } ] } ], } ]

這里的問題是,只有基本 class(BaseClass)的屬性被序列化(Id 和 Name)。 有沒有辦法用包含每個GenericDerivedClass<T>的信息(值)的List<BaseClass>序列化 class“MainClass”?

(使用List<object>而不是List<BaseClass>不是一種選擇,因為我不能使用原始類型。)

System.Text.Json 在設計上不支持它 但是可能有一種解決方法 - 如果您在Properties屬性之前添加[JsonIgnore]並添加一個屬性,例如

[JsonPropertyName] public IEnumerable<object> JsonProperties {get=> Items;}

請記住,您仍然無法反序列化它

奧利弗的評論讓我走上了正軌,謝謝。

我現在就這樣做:

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-6-0#support-polymorphic-deserialization

對於 go 來說,這有點過時了,但它似乎可以解決問題

暫無
暫無

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

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