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" }
Code language: JSON / JSON with Comments (json)

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);
Code language: C# (cs)

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.

2 thoughts on “JsonException: The JSON value could not be converted to Enum”

    • I mostly agree. Newtonsoft works as expected most of the time, whereas System.Text.Json’s default behavior is counter-intuitive in many cases. I think this is because it’s relatively new (compared with Newtonsoft). Hopefully Microsoft continues to improve it, and quickly.

      Reply

Leave a Reply to Marc Clifton Cancel reply