Enum converter for dictionary keys

This commit is contained in:
Alex
2025-01-16 15:45:26 +00:00
parent 0c08bac439
commit dbd3c18443
2 changed files with 15 additions and 2 deletions
+15 -1
View File
@@ -47,6 +47,20 @@ public class EftEnumConverter<T> : JsonConverter<T>
public override void WriteAsPropertyName(Utf8JsonWriter writer, [DisallowNull] T value, JsonSerializerOptions options)
{
writer.WritePropertyName(value.ToString());
object propertyValue = null;
if (typeof(T).GetFields().Any(f => f.FieldType == typeof(string)))
{
propertyValue = value as string;
}
else
{
if (typeof(T).GetFields().Any(f => f.FieldType == typeof(int)))
propertyValue = Convert.ToInt32(value);
else if (typeof(T).GetFields().Any(f => f.FieldType == typeof(byte)))
propertyValue = Convert.ToByte(value);
else
throw new Exception($"Could not convert enum {value.GetType()} with value {value}");
}
writer.WritePropertyName(propertyValue.ToString());
}
}
-1
View File
@@ -26,5 +26,4 @@ public class Test
var result = new JsonUtil().Serialize(_templates);
Console.WriteLine(result);
}
}