5

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"
 }
asked Nov 17, 2022 at 21:08

1 Answer 1

5

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.

answered Nov 17, 2022 at 21:43
2
  • 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! Commented Nov 17, 2022 at 22:05
  • 3
    You can configure those settings in startup.cs instead of adding the attribute over all enum fields in DTOs stackoverflow.com/questions/72060614/… Commented Nov 17, 2022 at 22:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.