Search code examples
c#.netgraphqljson.net

Custom StringEnumConverter is not picking up all Enums


I have a package of records for serialising and deserialising published in a private GitHub Repo for my project. Within one of them are a number of Enums. I am working with a GraphQL backend, and in GraphQL, the Enums are converted to upper case with underscores between words.

To deal with this, I have created an implementation of StringEnumConverter to take values like Regular to REGULAR and AnnualLeave to ANNUAL_LEAVE. These seem to work absolutely fine, however I have a status Enum which is Draft, however it is not going through the converter at all to change it to DRAFT.

Here is my WriteJson method which is reponsible for the work:

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        if (value is Enum enumValue)
        {
            var enumString = enumValue.ToString();
            var snakeCase = Regex.Replace(enumString, "([a-z])([A-Z])", "$1_$2").ToUpper();
            writer.WriteValue(snakeCase);
        }
        else
        {
            base.WriteJson(writer, value, serializer);
        }
    }

I've done some debugging with breakpoints and the first two, Regular and AnnualLeave hit the breakpoint fine, but Draft does not for some reason.

Can anyone offer any assistance as to why this might be happening, please?


Solution

  • For the Json, I use these JsonSerializerOptions:

    using System.Text.Json;
    using System.Text.Json.Serialization;
    
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseUpper) },
    };
    

    Json serializer options:

    • Indented for easy reading.
    • Properties in 'camelCase' instead of 'PascalCase'.
    • Ignore 'null' values for reference types and nullable value types.
    • Enum values as 'UPPER_SNAKE_CASE' instead of their int value.