Skip to content

Commit

Permalink
Merge pull request #67 from taks/enum-serialization
Browse files Browse the repository at this point in the history
Fix enum serialization
  • Loading branch information
xoofx committed Aug 4, 2023
2 parents a4faf8c + 3995a66 commit 3c221dd
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
22 changes: 22 additions & 0 deletions src/Tomlyn.Tests/ModelTests/ReflectionModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ private class TestConfigWithUri
public Uri? ServiceUri { get; set; }
}

[Test]
public void TestEnum()
{
var text = @$"enum_value = ""EnumValue1""";
var result = Toml.ToModel<TestConfigWithEnum>(text);
Assert.AreEqual(EnumType.EnumValue1, result.EnumValue);

var tomlText = Toml.FromModel(result);
Assert.AreEqual(text, tomlText.TrimEnd());
}

private enum EnumType
{
EnumValue0,
EnumValue1,
}

private class TestConfigWithEnum
{
public EnumType EnumValue { get; set; }
}

/// <summary>
/// Serialize back and forth all integer/float primitives.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Tomlyn/Model/Accessors/ReflectionObjectInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public ReflectionObjectInfo(ReflectionObjectKind kind, Type genericArgument1, Ty

public static ReflectionObjectInfo Get(Type type)
{
if (type == typeof(string) || type.IsPrimitive || type == typeof(TomlDateTime) || type == typeof(DateTime) || type == typeof(DateTimeOffset)
if (type == typeof(string) || type.IsPrimitive || type == typeof(TomlDateTime) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type.IsEnum
#if NET6_0_OR_GREATER
|| type == typeof(DateOnly) || type == typeof(TimeOnly)
#endif
Expand Down
4 changes: 4 additions & 0 deletions src/Tomlyn/Model/ModelToTomlTransform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,10 @@ private void WritePrimitive(object primitive, TomlPropertyDisplayKind displayKin
{
_writer.Write(TomlFormatHelper.ToString(dateTimeOffset, displayKind));
}
else if (primitive is Enum enumValue)
{
_writer.Write(TomlFormatHelper.ToString(enumValue.ToString(), displayKind));
}
#if NET6_0_OR_GREATER
else if (primitive is DateOnly dateOnly)
{
Expand Down

0 comments on commit 3c221dd

Please sign in to comment.