JsonException: The JSON value could not be converted to Enum

When you’re using System.Text.Json to deserialize JSON that contains the string representation of an enum, you get the following exception:

System.Text.Json.JsonException: The JSON value could not be converted to <Enum Type>

The following JSON would cause this exception. Conference is an enum, and this is using the string representation “NFC” instead of the numeric value of the enum.

{
  "TeamName": "Detroit Lions",
  "Conference": "NFC"
}

Solution

By default, System.Text.Json doesn’t handle enum strings.

You need to pass in a JsonStringEnumConverter via JsonSerializerOptions, and pass in the options when deserializing:

var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());

var team = JsonSerializer.Deserialize<NFLTeam>(json, options);

The same problem happens for serialization. If you don’t pass in the JsonStringEnumConverter, it’ll serialize objects with the enum numeric value, instead of their string representation.

Leave a Comment