< Summary

Information
Class: MRA.DTO.Enums.EnumStringJsonConverter<T>
Assembly: MRA.DTO
File(s): D:\a\MiguelRomerART\MiguelRomerART\MRA.DTO\Enums\EnumStringJsonConverter.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 15
Coverable lines: 15
Total lines: 48
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 14
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Read(...)0%210140%
Write(...)100%210%

File(s)

D:\a\MiguelRomerART\MiguelRomerART\MRA.DTO\Enums\EnumStringJsonConverter.cs

#LineLine coverage
 1using MRA.Infrastructure.Enums;
 2using System.ComponentModel;
 3using System.Reflection;
 4using System.Text.Json;
 5using System.Text.Json.Serialization;
 6
 7namespace MRA.DTO.Enums;
 8
 9public class EnumStringJsonConverter<TEnum> : JsonConverter<TEnum> where TEnum : struct, Enum
 10{
 11    public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
 12    {
 013        if (reader.TokenType == JsonTokenType.String)
 14        {
 015            var stringValue = reader.GetString();
 16
 017            foreach (var field in typeof(TEnum).GetFields())
 18            {
 019                var descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>();
 020                if (descriptionAttribute != null && descriptionAttribute.Description == stringValue)
 21                {
 022                    return (TEnum)field.GetValue(null);
 23                }
 24            }
 25
 026            if (Enum.TryParse(stringValue, true, out TEnum result))
 27            {
 028                return result;
 29            }
 30        }
 31
 032        if (reader.TokenType == JsonTokenType.Number)
 33        {
 034            var intValue = reader.GetInt32();
 035            if (Enum.IsDefined(typeof(TEnum), intValue))
 36            {
 037                return (TEnum)Enum.ToObject(typeof(TEnum), intValue);
 38            }
 39        }
 40
 041        return EnumExtensions.GetDefaultValue<TEnum>();
 42    }
 43
 44    public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options)
 45    {
 046        writer.WriteStringValue(value.ToString());
 047    }
 48}