Home > other >  System.Text.Json: How to serialize an enum dictionary key as number
System.Text.Json: How to serialize an enum dictionary key as number

Time:12-06

Is it possible to serialize an enum dictionary key as a number? Example:

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

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

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

CodePudding user response:

You can write your custom converter which will support writing dictionary keys:

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"));
}

And example usage (or pass in settings for Serialize method):

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

Or use JsonStringEnumMemberConverter from Macross.Json.Extensions which scans for EnumMemberAttribute:

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

CodePudding user response:

Yes, it is possible to serialize an enum dictionary key as a number. In the example you provided, the JsonSerializer would serialize the Dictionary<MyEnum, int> object into a JSON string with the enum values as the keys, like this: {"1":1,"2":2}.

To do this, the JsonSerializer needs to be configured to use the EnumMember attribute when serializing the enum values. This attribute allows you to specify the name or value of an enum member that will be used during serialization and deserialization.

Here is an example of how you can use the EnumMember attribute to configure the JsonSerializer to serialize the enum values as numbers:

public enum MyEnum
{
  [EnumMember(Value = "1")]
  One = 1,

  [EnumMember(Value = "2")]
  Two = 2
}

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

In this example, the JsonSerializer will serialize the enum values as strings, using the values specified in the EnumMember attributes (i.e., "1" and "2"). The resulting JSON string will be the same as the one in your example: {"1":1,"2":2}.

  • Related