System.Text.Json 序列/反序列化 abstract class

    public enum SKUTypes
    {
        /// 
        /// 普通,SKU 的价格直接体现在 SKU 中
        /// 
        Normal = 0,

        /// 
        /// 日历类型,SKU 的价格需要从日历价格接口中取
        /// 
        Daily = 1,

        /// 
        /// 需要选择日期的, 比如酒店, 需要选择日期才能查价格
        /// 
        ChoiceDate = 2
    }
    [JsonConverter(typeof(SKUConverter))]
    public abstract class BaseSKU
    {
        /// 
        /// 是否是日历类型的 SKU
        /// 
        public abstract SKUTypes SKUType { get; }
...
...
    public class SKU : BaseSKU
    {
        /// 
        /// 
        /// 
        public override SKUTypes SKUType => SKUTypes.Normal;
...
...
    public class DailySKU : BaseSKU
    {
        /// 
        /// 
        /// 
        public override SKUTypes SKUType => SKUTypes.Daily;
...
...
    public class SKUConverter : JsonConverter
    {

        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public override BaseSKU Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            //reader 是 struct , 如果直接用 reader 的话, 会因为位置已改变, 下面的 Deserializer 报错
            var tmpReader = reader;
            var detect = JsonSerializer.Deserialize(ref tmpReader, options);


            return detect.SKUType switch
            {
                SKUTypes.Daily => (BaseSKU)JsonSerializer.Deserialize(ref reader, typeof(DailySKU), options),
                SKUTypes.Normal => (BaseSKU)JsonSerializer.Deserialize(ref reader, typeof(SKU), options),
                SKUTypes.ChoiceDate => (BaseSKU)JsonSerializer.Deserialize(ref reader, typeof(HotelSKU), options),
                _ => throw new NotSupportedException($"SKUType:{detect.SKUType}"),
            };
        }

        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public override void Write(Utf8JsonWriter writer, BaseSKU value, JsonSerializerOptions options)
        {
            JsonSerializer.Serialize(writer, value, value?.GetType() ?? typeof(object), options);
        }



        /// 
        /// 
        /// 
        private class TypeDetectSKU : BaseSKU
        {
            /// 
            /// 
            /// 
            [JsonPropertyName("SKUType")]
            public SKUTypes _SKUType { get; set; }

            /// 
            /// 
            /// 
            [JsonIgnore]
            public override SKUTypes SKUType => this._SKUType;
        }
    }

你可能感兴趣的:(System.Text.Json 序列/反序列化 abstract class)