How to serialize an Enum with a custom string name using System.Text.Json

329 Views Asked by At

I have some problems when customizing Enum values as a string.

public sealed class SerializationTest
{
    [JsonPropertyName("type")]
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public SerializationType Type { get; set; }
}


public enum SerializationType
{
    [EnumMember(Value = "system_serialization")]
    System = 1,

    [EnumMember(Value = "custom_serialization")]
    Custom = 2
}

Look at the example above. I have an Enum with two values: System and Custom. But I want to change the name when the serialization occurs:

  • System -> system_serialization
  • Custom -> custom_serialization

I tried using a specific JsonSerializerOptions with a JsonStringEnumConverter but it doesn't work.

When I try to serialize the SerializationTest object the process doesn't work. I'm trying something like this:

.
.
.
var myObject = new SerializationTest
{
    Type = SerializationType.System
};

var content = JsonSerializer.Serialize(myObject);
.
.
.

I'm getting the following results: {"type":"System"} But I need: {"type":"system_serialization"}

Can someone help me?

1

There are 1 best solutions below

2
On

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

public sealed class SerializationTest
{
    [JsonPropertyName("type")]
    [JsonConverter(typeof(JsonStringEnumMemberConverter))] 
    public SerializationType Type { get; set; }
}

Alternatively you can write your own custom converter (or better converter factory) which will read the attributes and read/write them.