| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Text.Json.Serialization.Converters; |
| | | 5 | | |
| | | 6 | | namespace System.Text.Json.Serialization |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Converter to convert enums to and from numeric values. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <typeparam name="TEnum">The enum type that this converter targets.</typeparam> |
| | | 12 | | /// <remarks> |
| | | 13 | | /// This is the default converter for enums and can be used to override |
| | | 14 | | /// <see cref="JsonSourceGenerationOptionsAttribute.UseStringEnumConverter"/> |
| | | 15 | | /// on individual types or properties. |
| | | 16 | | /// </remarks> |
| | | 17 | | public sealed class JsonNumberEnumConverter<TEnum> : JsonConverterFactory |
| | | 18 | | where TEnum : struct, Enum |
| | | 19 | | { |
| | | 20 | | /// <summary> |
| | | 21 | | /// Initializes a new instance of <see cref="JsonNumberEnumConverter{TEnum}"/>. |
| | | 22 | | /// </summary> |
| | 0 | 23 | | public JsonNumberEnumConverter() { } |
| | | 24 | | |
| | | 25 | | /// <inheritdoc /> |
| | 0 | 26 | | public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(TEnum); |
| | | 27 | | |
| | | 28 | | /// <inheritdoc /> |
| | | 29 | | public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 30 | | { |
| | 0 | 31 | | if (typeToConvert != typeof(TEnum)) |
| | 0 | 32 | | { |
| | 0 | 33 | | ThrowHelper.ThrowArgumentOutOfRangeException_JsonConverterFactory_TypeNotSupported(typeToConvert); |
| | | 34 | | } |
| | | 35 | | |
| | 0 | 36 | | return EnumConverterFactory.Helpers.Create<TEnum>(EnumConverterOptions.AllowNumbers, options); |
| | 0 | 37 | | } |
| | | 38 | | } |
| | | 39 | | } |