Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Json.Net Deserializes enum value as integer and accepts as valid?

I am confused about how Json.NET serializes/deserializes enums.

I have this field in my JSON Schema:

"MyEnumValue": {
    "type": "string",
    "enum": ["D", "F", "R"]
},

and this C# code:

[JsonProperty(PropertyName = "MyEnumValue", Required = Required.Always)]
public MyEnumValue MyEnumValue { get; set; } 

public enum MyEnumValue 
{
    D, F, R
}

When I use this function:

JsonConvert.SerializeObject

The created Json text contains this:

"MyEnumValue":82

So JSON.NET deserializes an enum value that expects char as an integer which is an ASCII value of a char.

My questions are: * Why don't I get the char only by Serializing?

  • Is it normal for (Universal) JSON Schema rules?
like image 608
Hakan Avatar asked Dec 20 '25 03:12

Hakan


1 Answers

If you need to [de]serialize the enum as string, add this to the property:

[JsonProperty(PropertyName = "Enum", Required = Required.Always)]
[JsonConverter(typeof(StringEnumConverter))]
public MyEnumValue MyEnumValue { get; set; } 
like image 164
Xiaoy312 Avatar answered Dec 22 '25 16:12

Xiaoy312



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!