Skip to content

SmartEnumValueConverter does not write the value as a number for TValue of type byte or sbyte #560

@Venom1991

Description

@Venom1991

Take for example the second smart enum from the Usage section of this project's readme file with the only difference being that the TValue is of type byte:

using Ardalis.SmartEnum;

public sealed class TestEnum : SmartEnum<TestEnum, byte>
{
    public static readonly TestEnum One = new TestEnum("A string!", 1);
    public static readonly TestEnum Two = new TestEnum("Another string!", 2);
    public static readonly TestEnum Three = new TestEnum("Yet another string!", 3);

    private TestEnum(string name, byte value) : base(name, value)
    {
    }
}

Serialization works fine but the problem happens during deserialization because the enum member's value is actually written as a string instead of a number.
Specifically, an exception (InvalidOperationException) is thrown with the message:
"Cannot get the value of a token type 'String' as a number".

This is because (as far as I can tell) the converter's Write() method does not handle cases in which TValue is defined as byte or sbyte. Funnily enough, the ReadValue() method actually does just that!

Also, it seems that the decimal type is being handled in Write() but not in ReadValue().

So, a workaround (until this issue is addressed) would be either using any other number type (integer or floating point) or perhaps defining this JSON serializer setting as "AllowReadingFromString".

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions