當我建立了兩個分別使用不同 ITag 實作的物件 John 和 Mary,並使用 System.Text.Json 的 JsonSerializer 序列化輸出時,實際上輸出的結果和希望得到的有了落差,因為序列化時,會使用 ITag 做處理,造成使用 ATag 實作的輸出少了 Age 屬性,使用 BTag 實作的輸出少了 Gender 屬性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var john = new People(); john.Card = new ATag { Name = "John", Age = 20, }; var mary = new People(); mary.Card = new BTag { Name = "Mary", Gender = "Female", };
voidMain() { var john = new People(); john.Card = new ATag { Name = "John", Age = 20, }; var mary = new People(); mary.Card = new BTag { Name = "Mary", Gender = "Female", }; var option = new JsonSerializerOptions(); option.Converters.Add(new ITagConverter()); JsonSerializer.Serialize(john, option).Dump(); JsonSerializer.Serialize(mary, option).Dump(); }
publicclassITagConverter : JsonConverter<ITag> { publicoverride ITag Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { thrownew NotImplementedException(); } publicoverridevoidWrite(Utf8JsonWriter writer, ITag value, JsonSerializerOptions options) { switch (value) { case ATag tag: JsonSerializer.Serialize(writer, tag, options); break; case BTag tag: JsonSerializer.Serialize(writer, tag, options); break; default: thrownew ArgumentException(message: "It is not a recognized type.", paramName: nameof(value)); } } }