C# 10 - implementing Custom JSON Converter for Enums in System.Text.Json
I'm optimizing some code but I'm integrating two systems and I'm working on a personal project and I'm trying to implement a custom JSON converter for an enum type in my C# 10 application using System.Text.Json. I want to ensure that when the enum is serialized, it uses a specific string format instead of the default integer values. However, I'm working with an scenario where the deserialization fails with the behavior message: `System.Text.Json.JsonException: The JSON value is not valid. Expected a string but got 'null'`. Here's the code I've implemented for the converter: ```csharp public class CustomEnumConverter : JsonConverter<MyEnum> { public override MyEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return default; // Handle null case } if (reader.TokenType == JsonTokenType.String) { string value = reader.GetString(); return Enum.TryParse(value, out MyEnum result) ? result : throw new JsonException(); } throw new JsonException(); } public override void Write(Utf8JsonWriter writer, MyEnum value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } } ``` I have registered this converter in the `JsonSerializerOptions` as follows: ```csharp var options = new JsonSerializerOptions { Converters = { new CustomEnumConverter() } }; var json = JsonSerializer.Serialize(myObject, options); var deserializedObject = JsonSerializer.Deserialize<MyClass>(json, options); ``` The serialization works fine, but the deserialization is throwing the behavior when the JSON string contains a null value for the enum. I tried adding a check for `JsonTokenType.Null`, but it still doesn't seem to work as expected. Is there something I'm missing in the deserialization logic? How can I properly handle null values during the deserialization process for my enum? What's the best practice here? What are your experiences with this? I recently upgraded to C# 3.11. For reference, this is a production desktop app. Is there a better approach?