How to serialize enum to int #863
-
public enum TestEnum
{
TypeA=0,
TypeB=1,
TypeC=2,
TypeD=3,
} public class TestClass
{
public TestEnum Type { get; set; }
} var data = new TestClass
{
Type = TestEnum.TypeC
};
var serializer = new SerializerBuilder().Build();
var content = serializer.Serialize(data);
Console.WriteLine(content); output
What I expect is
|
Beta Was this translation helpful? Give feedback.
Answered by
EdwardCooke
Nov 14, 2023
Replies: 2 comments
-
I don't think it does this out of the box, nor do I think there is an option for it. You could create a custom type converter for it though. Here's a very basic example. In the accepts type you could do a |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
GardenHamster
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think it does this out of the box, nor do I think there is an option for it. You could create a custom type converter for it though.
Here's a very basic example.
https://github.com/aaubry/YamlDotNet/blob/master/YamlDotNet/Serialization/Converters/GuidConverter.cs
In the accepts type you could do a
type.IsEnum
or something like that and write out an scalar with the int version of the enum in the WriteYaml and read in a Scalar as the int and parse it through Enum.TryParse (or something like that) and return that value.