I have the following class:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class JsonError
{
[JsonConverter(typeof(StringEnumConverter))]
public enum Number
{
[EnumMember(Value = "0")]
Pass,
[EnumMember(Value = "1")]
Miscalc,
[EnumMember(Value = "2")]
ReadError
}
public Number ErrorNumber { get; set; }
}
And I try to deserialize this JSON file...
{
"CriticalErrors": [
{
"ErrorNumber": "1"
},
{
"ErrorNumber": "2"
}
]
}
... into this class:
public class TestBehavior
{
public List<JsonError> CriticalErrors { get; set; } = new List<JsonError>();
}
But I get this error: "The JSON value could not be converted to MyNamespace.JsonError+Number. Path: $.CriticalErrors[0].ErrorNumber | LineNumber: 3 | BytePositionInLine: 24."
Any ideas what could have gone wrong? The values "1" and "2" obviously exist in the enum, and the format seems correct. Unfortunately, the error message does not tell me what exactly has gone wrong, so I am quite lost here.
TL;DR: Your problem is that you are actually using System.Text.Json not Json.NET to deserialize your JSON, and System.Text.Json does not support use of
EnumMemberAttributeto specify custom names for enums. (Demo fiddle here).To use
EnumMemberAttributeyou must either:How to determine the serializer used?. There are two JSON serializers widely used in .NET Core: System.Text.Json and Json.NET. If an exception is thrown while deserializing JSON, and
System.Text.Json(e.g.System.Text.Json.JsonException), ORLineNumberandBytePositionInLine, e.g.LineNumber: 3 | BytePositionInLine: 24.Then the error was generated by System.Text.Json.
If an exception is thrown and
Newtonsoft.Json(e.g.Newtonsoft.Json.JsonSerializationException, ORlineandposition, e.g.line 4, position 28.Then the error was generate by Json.NET.
BytePositionInLinewill only ever be reported by System.Text.Json because it deserializes directly from UTF8bytestreams and thus has information about byte positioning. Conversely Json.NET deserializes from UTF16charstreams, and so does not have information about byte positioning, just character positioning.