Unable to deserialize char-based Enum
Description
In one of our APIs we have an endpoint that returns data that contains an enum; this enum is returned in JSON as a string (e.g.: "Color" : "B"). When trying to deserialize the enum it fails.
Reproduction Steps
Have an enum which has it's values defined as chars:
public enum UserAnswer
{
Yes = 'Y',
No = 'N'
}
The API response model contains said enum:
public class APIResponse
{
public UserAnswer Answer { get; init; }
}
The Json string contains the enum value formatted as a string:
{
"Answer" : "N"
}
When trying to deserialize an exception is thrown:
using System.Text.Json;
// ...
// throws "System.Text.Json.JsonException: The JSON value could not be converted to Sandbox.Program+UserAnswer"
var deserializedObject = JsonSerializer.Deserialize<APIResponse>(jsonString);
Decorating the enum with [JsonConverter(typeof(JsonStringEnumConverter))] doesn't help, neither does decorating the values with [EnumMember(Value = "<value>")]
Expected behavior
When a Json value is a single character that matches values in the enum, the enum should receive that value. That is, when (in the example given) the Json is:
{
"Answer" : "N"
}
The deserialized Answer should have value UserAnswer.No; likewise, with:
{
"Answer" : "Y"
}
Answer should have value UserAnswer.Yes.
Actual behavior
An exception is thrown.
Regression?
No response
Known Workarounds
No response
Configuration
Which version of .NET is the code running on? .NET 6, .NET 5. What OS and version, and what distro if applicable? Windows 10 21H1 (19043.1645). What is the architecture (x64, x86, ARM, ARM64)? x64. Do you know whether it is specific to that configuration? No. If you're using Blazor, which web browser(s) do you see this issue in? n/a.
Other information
No response
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in area-owners.md if you want to be subscribed.
Issue Details
Description
In one of our APIs we have an endpoint that returns data that contains an enum; this enum is returned in JSON as a string (e.g.: "Color" : "B"). When trying to deserialize the enum it fails.
Reproduction Steps
Have an enum which has it's values defined as chars:
public enum UserAnswer
{
Yes = 'Y',
No = 'N'
}
The API response model contains said enum:
public class APIResponse
{
public UserAnswer Answer { get; init; }
}
The Json string contains the enum value formatted as a string:
{
"Answer" : "N"
}
When trying to deserialize an exception is thrown:
using System.Text.Json;
// ...
// throws "System.Text.Json.JsonException: The JSON value could not be converted to Sandbox.Program+UserAnswer"
var deserializedObject = JsonSerializer.Deserialize<APIResponse>(jsonString);
Decorating the enum with [JsonConverter(typeof(JsonStringEnumConverter))] doesn't help, neither does decorating the values with [EnumMember(Value = "<value>")]
Expected behavior
When a Json value is a single character that matches values in the enum, the enum should receive that value. That is, when (in the example given) the Json is:
{
"Answer" : "N"
}
The deserialized Answer should have value UserAnswer.No; likewise, with:
{
"Answer" : "Y"
}
Answer should have value UserAnswer.Yes.
Actual behavior
An exception is thrown.
Regression?
No response
Known Workarounds
No response
Configuration
Which version of .NET is the code running on? .NET 6, .NET 5. What OS and version, and what distro if applicable? Windows 10 21H1 (19043.1645). What is the architecture (x64, x86, ARM, ARM64)? x64. Do you know whether it is specific to that configuration? No. If you're using Blazor, which web browser(s) do you see this issue in? n/a.
Other information
No response
| Author: | WashingtonARamos |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
That enum doesn't contain chars. Its underlying type is Int32, and the values in the enum are just cast from char. At the IL level it's indistinguishable: https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABATARgLABQhGAzAAQwB2ArgLZkCqAzjFAIKVMDurhA3oTJCyATRhMyAXjIByETIA0g4QDkIU2SpmEAvkA
@stephentoub by decorating the enum values with [EnumMember(Value = "<value>"] on Newtonsoft.Json I can make it work:
public enum UserAnswer
{
[EnumMember(Value = "Y")]
Yes,
[EnumMember(Value = "N")]
No
}
The same doesn't work on System.Text.Json, as it throws the same System.Text.Json.JsonException. Is it a missing feature?
@WashingtonARamos yeah it's currently not supported. Using EnumMemberAttribute for System.Text.Json was tracked in #31081
Workaround I found in that issue is to use https://www.nuget.org/packages/Macross.Json.Extensions/ and JsonStringEnumMemberConverter to the converters until (when/if) it's supported.
https://www.nuget.org/packages/Json.More.Net/ also has a string converter (I imagine they're fairly common).
@lilinus I tried EnumExtensions.System.Text.Json for that and it had a little problem, when a string was an int it would treat it as it's internal enum value instead of the "referenced" value, say I have an enum:
public enum MyEnum
{
[EnumMember(Value = "1")] // "reference" value = "1"
EnumX, // Internally = 0
[EnumMember(Value = "2")] // "reference" value = "2"
EnumY // Internally = 1
}
So that if I tried to deserialize { MyEnum = "1" } it would deserialize as EnumY instead of EnumX. Macross.Json.Extensions on the other hand does what I expect it to do. In production tho I've already written a custom JsonConverter specifically for our use case, but it's good to have these cases documented in case someone in the future finds themselves having the same issue. :)
by decorating the enum values with
[EnumMember(Value = "<value>"]onNewtonsoft.JsonI can make it work:
We don't have any plans on supporting System.Runtime.Serialization attributes natively in STJ, but want to provide extensibility points that make such support possible via community provided extensions. Supporting EnumMemberAttribute should be possible using a custom converter factory (as seems to have already been done in some of the packages listed here).
At risk of stating the obvious, one alternative approach might be to use a dedicated enum type in your DTO layer:
[JsonConverter(JsonStringEnumConverter)]
public enum UserAnswerDto { Y, N }
by decorating the enum values with
[EnumMember(Value = "<value>"]onNewtonsoft.JsonI can make it work:We don't have any plans on supporting System.Runtime.Serialization attributes natively in STJ, but want to provide extensibility points that make such support possible via community provided extensions. Supporting
EnumMemberAttributeshould be possible using a custom converter factory (as seems to have already been done in some of the packages listed here).At risk of stating the obvious, one alternative approach might be to use a dedicated enum type in your DTO layer:
[JsonConverter(JsonStringEnumConverter)] public enum UserAnswerDto { Y, N }
Sorry for reopening the issue but at times it would be unviable to simply list the pure enum values ("Y","N"). It would either be literally impossible due to language limitations or it would kill code readability. One such case is to enum a FIX Order Status. Since enum names can't be numbers we wouldn't be able to directly list from New ('0') to Suspended ('9') and even if we could a code read like this:
if (orderStatus == OrderStatus.0 || orderStatus == OrderStatus.D)
{
// ...
}
Would be horrible. Also, since we can't set the enum values directly as chars (public enum OrderStatus { New = '0', PartiallyFilled = '1' }) in this case we need something else. It would be nice to have something out of the box so that we don't have to depend on third party libs for such a small feature. Still, it was indeed easy to write a custom JsonConverter for our use case, but not before researching for ways to solve in vanilla .NET and third party libs.