CodexBloom - Programming Q&A Platform

implementing Custom JSON Converter for Enum Handling in System.Text.Json - Not Serializing Properly

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
c# json enum system.text.json C#

I just started working with I'm getting frustrated with I've been banging my head against this for hours... I've searched everywhere and can't find a clear answer. I'm working with a question when using a custom JSON converter for an enum in my .NET 6 application. I implemented the converter to serialize the enum values as strings instead of their integer representations. However, when I deserialize the JSON back into my objects, it throws a `JsonException`. Here’s the code for my enum and the custom converter: ```csharp public enum OrderStatus { Pending, Completed, Cancelled } public class Order { public int Id { get; set; } public OrderStatus Status { get; set; } } public class OrderStatusJsonConverter : JsonConverter<OrderStatus> { public override OrderStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var value = reader.GetString(); return Enum.Parse<OrderStatus>(value); } public override void Write(Utf8JsonWriter writer, OrderStatus value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } } ``` I registered the converter in my `Startup.cs` like this: ```csharp services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new OrderStatusJsonConverter()); }); ``` When I try to deserialize a JSON string like this: ```json {"Id": 1, "Status": "Completed"} ``` I get the following behavior: ``` System.Text.Json.JsonException: The JSON value could not be converted to OrderStatus. Path: $.Status | Line: 1 | Position: 20. ``` I've confirmed that the string "Completed" matches the enum value, so I suspect it might be an scenario with how the converter is registered or used. I've tried cleaning the solution and restarting the application, but the scenario continues. Any advice on how to resolve this? I'm working on a CLI tool that needs to handle this. Is there a better approach? I'm open to any suggestions. This is my first time working with C# stable.