反序列化enum

   [JsonConverter(typeof(EnumJsonConverter<DocumentStatus>))]
   public enum DocumentStatus
   {
       None = 0,
       Rejected = 1,
       Approved = 2,
       Published = 3,
   }

    public class EnumJsonConverter<T> : JsonConverter<T> where T : struct, Enum
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            string value = reader.GetString();
            if (Enum.TryParse(value, out T result))
            {
                return result;
            }
            throw new ArgumentException($"Invalid {typeof(T).Name} value");
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }
posted @ 2024-12-24 15:13  Josen_Earth  阅读(1)  评论(0编辑  收藏  举报