可以将枚举字典键序列化为数字吗?例如:
public enum MyEnum { One = 1, Two = 2 } JsonSerializer.Serialize(new Dictionary<MyEnum, int> { [MyEnum.One] = 1, [MyEnum.Two] = 2 }); Output: {"1":1,"2":2}
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方法的设置):
Serialize
[JsonConverter(typeof(JsonEnumNumberConverter))] public enum MyEnum { One = 1, Two = 2 }
或者使用Macross.Json.Extensions中的JsonStringEnumMemberConverter,它扫描EnumMemberAttribute:
Macross.Json.Extensions
JsonStringEnumMemberConverter
EnumMemberAttribute
[JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumMemberConverter))] public enum MyEnum { [EnumMember(Value = "1")] One, [EnumMember(Value = "2")] Two }
1条答案
按热度按时间5sxhfpxr1#
您可以编写支持编写字典键的自定义转换器:
示例用法(或传入
Serialize
方法的设置):或者使用
Macross.Json.Extensions
中的JsonStringEnumMemberConverter
,它扫描EnumMemberAttribute
: