3

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"
    }
Russ
  • 12,312
  • 20
  • 59
  • 78

1 Answers1

4

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.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
  • 1
    Thanks @Poul, I had tried each of these individually, but not together. I'm a bit sad given how many enums I need to touch in this project, but that's an implementation detail. Thanks again! – Russ Nov 17 '22 at 22:05
  • 2
    You can configure those settings in startup.cs instead of adding the attribute over all enum fields in DTOs https://stackoverflow.com/questions/72060614/asp-net-core-6-how-to-update-option-for-json-serialization-date-format-in-json – Yevhen Cherkes Nov 17 '22 at 22:44