kyy
2025-07-02 07558e32634314eec359ec8437d97bdc5def64f9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright © 2021 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
 
using System;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
 
namespace CefSharp.Internals.Json
{
    /// <summary>
    /// DevTools Json Enum Converter Factory
    /// </summary>
    public class JsonEnumConverterFactory : JsonConverterFactory
    {
        /// <inheritdoc/>
        public override bool CanConvert(Type typeToConvert)
        {
            if(typeToConvert.IsEnum)
            {
                return true;
            }
 
            var nullType = Nullable.GetUnderlyingType(typeToConvert);
 
            return nullType?.IsEnum ?? false;
        }
 
        /// <inheritdoc/>
        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            var converter = (JsonConverter)Activator.CreateInstance(
                typeof(JsonEnumConverter<>).MakeGenericType(typeToConvert),
                BindingFlags.Instance | BindingFlags.Public,
                binder: null,
                args: null,
                culture: null);
 
            return converter;
        }
 
        public static object ConvertStringToEnum(string val, Type typeToConvert)
        {
            foreach (var name in Enum.GetNames(typeToConvert))
            {
                var attribute = typeToConvert.GetField(name)
                    .GetCustomAttributes(false)
                    .OfType<JsonPropertyNameAttribute>()
                    .Single();
 
                if (attribute.Name == val)
                {
                    return Enum.Parse(typeToConvert, name);
                }
            }
 
            throw new JsonException("Unable to convert Enum");
        }
 
        public static string ConvertEnumToString(object value)
        {
            var type = value.GetType();
            var name = Enum.GetName(type, value);
            var attribute = type.GetField(name)
                .GetCustomAttributes(false)
                .OfType<JsonPropertyNameAttribute>()
                .Single();
 
            return attribute.Name;
        }
    }
}