JsonConverter fails with nullable enums. #102042
-
DescriptionWe need a JsonConverter to use with all Enums in our solution(s), some of which are nullable. I can get it to work, except with nullable enums as shown below. Reproduction Stepspublic class JsonEnumTypeConverter : JsonConverter<Enum>
{
public override bool HandleNull => true;
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.IsEnum ||
(IsNullableType(typeToConvert) && Nullable.GetUnderlyingType(typeToConvert)!.IsEnum);
}
public override Enum? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Custom reading stuff that has to be done to ALL enums.
}
public override void Write(Utf8JsonWriter writer, Enum? value, JsonSerializerOptions options)
{
writer.WriteStringValue(value is null ? "null" : value.ToString());
}
private static bool IsNullableType(Type t)
{
return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>);
}
}
public enum AnEnum
{
One,
Two,
Three
}
public class ThisWorks
{
public AnEnum TheEnum { get; set; }
}
public class ThisFails
{
public AnEnum? TheEnum { get; set; }
}
///////////////////////////////////
var options = new JsonSerializerOptions()
options.Converters.Add(new JsonEnumTypeConverter));
var json = @" ""theEnum"": ""One"" ";
// this works
var deserialized1 = JsonSerializer.Deserialize<ThisWorks>(json, options);
// The converter 'JsonEnumTypeConverter' is not compatible with the type 'System.Nullable`1[AnEnum]'
var deserialized2 = JsonSerializer.Deserialize<ThisFails>(json, options); Expected behaviorIt should handle both non-nullable and nullable enums. Actual behaviorFails on nullable enums. Regression?No response Known WorkaroundsNo response Configuration.NET version = 8. Other informationNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis |
Beta Was this translation helpful? Give feedback.
-
A
If you need more customization, it's suggested to start from the source code of |
Beta Was this translation helpful? Give feedback.
-
So if I'm reading the code right (debatable), I will need a The reason for all of this, BTW, is because all of our domain Enums have -1 (Unknown) and 0 (NotSet) default values, and the JSON reader need to default to -1 if it doesn't recognise it (which I've argued against, but that's another story). Some of them are nullable.... |
Beta Was this translation helpful? Give feedback.
-
Nullability for enums and other structs is handled automatically via the serializer, but it doesn't like having a single, untyped converter for all enums.
|
Beta Was this translation helpful? Give feedback.
-
Ahhhhhh that explains a lot, thanks! |
Beta Was this translation helpful? Give feedback.
Nullability for enums and other structs is handled automatically via the serializer, but it doesn't like having a single, untyped converter for all enums.