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?
You can use
JsonStringEnumMemberConverter
fromMacross.Json.Extensions
which scans forEnumMemberAttribute
:Alternatively you can write your own custom converter (or better converter factory) which will read the attributes and read/write them.