The JSON value could not be converted to Enum
By FoxLearn 3/21/2025 2:13:48 AM 75
System.Text.Json.JsonException: The JSON value could not be converted to <Enum Type>
This issue arises when the JSON data includes an enum in string form, rather than its numeric value.
For example, consider the following JSON, where Conference
is an enum, and its value is represented as a string ("NFC") instead of the corresponding numeric value:
{ "TeamName": "Detroit", "Conference": "NFC" }
Solution
By default, System.Text.Json
does not support deserializing enums in string form.
To fix this, you need to add a JsonStringEnumConverter
to JsonSerializerOptions
and use these options when deserializing:
var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); var team = JsonSerializer.Deserialize<NFLTeam>(json, options);
Similarly, if you are serializing an object with an enum property into JSON, and you don't use the JsonStringEnumConverter
, the enum will be serialized as its numeric value instead of its string representation.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization