System.Text.Json:如何将枚举字典键序列化为数字

uidvcgyl  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(168)

可以将枚举字典键序列化为数字吗?例如:

public enum MyEnum
{
  One = 1,
  Two = 2
}

JsonSerializer.Serialize(new Dictionary<MyEnum, int>
{
   [MyEnum.One] = 1,
   [MyEnum.Two] = 2
});

Output:
{"1":1,"2":2}
5sxhfpxr

5sxhfpxr1#

您可以编写支持编写字典键的自定义转换器:

class JsonEnumNumberConverter : JsonConverter<MyEnum>
{
    public override MyEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();

    public override void Write(Utf8JsonWriter writer, MyEnum value, JsonSerializerOptions options) => throw new NotImplementedException();

    public override void WriteAsPropertyName(Utf8JsonWriter writer, MyEnum value, JsonSerializerOptions options) =>
         writer.WritePropertyName(value.ToString("D"));
}

示例用法(或传入Serialize方法的设置):

[JsonConverter(typeof(JsonEnumNumberConverter))]
public enum MyEnum
{
    One = 1,
    Two = 2
}

或者使用Macross.Json.Extensions中的JsonStringEnumMemberConverter,它扫描EnumMemberAttribute

[JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumMemberConverter))]  
public enum MyEnum
{
    [EnumMember(Value = "1")]
    One,
    [EnumMember(Value = "2")]
    Two
}

相关问题