Russ
Russ

Reputation: 12530

How to handle stringified numeric enum with System.Text.Json

I have been tasked with trying to migrate an existing application to System.Text.Json in .NET 6. One of the challenges is that I receive json from the front end of the application incorrectly, BUT Newtonsoft is able to handle it.

The first problem I am running into, which is blocking me from finding anything else, is regarding enums.

In the below example, I am getting the numeric value for an enum, however it's being presented as a string from the frontend. Because of this System.Text.Json is unable to parse the value.

I have been playing with custom converters, but so far no luck.

        C#:
     public enum OperationType
        {
            Undefined = 0,
            InnerJoin = 1,            
        }
    
     public class ExampleClass
        {
            public OperationType Operation { get; set; }
        }
    
    Invalid, how do I handle this?
    {
        "operation" : "1"
    }

Valid JSON
    {
        "operation" : 1
    }
    
    Valid JSON
    {
        "operation" : "InnerJoin"
    }

Upvotes: 5

Views: 2349

Answers (1)

Poul Bak
Poul Bak

Reputation: 10929

You need to apply a JsonSerializerOptions to the Deserialize method as well as a JsonConverter attribute to the enum declaration, like this:

string json = @"{""operation"" : ""1""}";

JsonSerializerOptions jsonSerializerOptions = new()
{ 
    NumberHandling = JsonNumberHandling.AllowReadingFromString,
    PropertyNameCaseInsensitive = true
};

ExampleClass? example = JsonSerializer.Deserialize<ExampleClass>(json, jsonSerializerOptions);
Debug.WriteLine(example?.Operation);

public class ExampleClass
{
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public OperationType Operation
    {
        get; set;
    }
}

Now you should be able read enum values given as quoted numbers.

Upvotes: 5

Related Questions