Skip to content

JsonConverter fails with nullable enums. #102042

Closed Answered by gregsdennis
foggerty asked this question in Q&A
Discussion options

You must be logged in to vote

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.

  1. Write your converter to be generic where the generic parameter must be an enum:
    public class JsonEnumTypeConverter<T> : JsonConverter<T> where T : Enum
    {
        // remove CanConvert() override
    }
  2. Include instances of your converter for each enum type you want to convert. This can be done as a list or with reflection.
    options.Converters.Add(new JsonEnumTypeConverter<AnEnum>());
    options.Converters.Add(new JsonEnumTypeConverter<AnotherEnum>());
    
    // or
    
    var converters = typeof(AnEnum).Assembly
        .DefinedTypes
        .Where(t => t.IsEnum)
        .S…

Replies: 5 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by eiriktsarpalis
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
3 participants
Converted from issue

This discussion was converted from issue #102006 on May 09, 2024 13:14.