The JSON value could not be converted to Enum

By FoxLearn 3/21/2025 2:13:48 AM   75
When using System.Text.Json to deserialize JSON that includes a string representation of an enum, you may encounter the following error:
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.