-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Description
When you deserialize an invalid enum member, you get an error message like this:
The JSON value could not be converted to TestProject1.CustomEnum1. Path: $.Value | LineNumber: 0 | BytePositionInLine: 16.
This is not helpful as it requires additional work to track down the offending value.
The error message should be improved to:
System.Text.Json.JsonException: The JSON value 'InvalidValue' could not be converted to TestProject1.CustomEnum2. Path: $.Value | LineNumber: 0 | BytePositionInLine: 16.
Reproduction Steps
using System.Text.Json.Serialization;
using System.Text.Json;
namespace TestProject1 {
[TestClass]
public sealed class Test1 {
private static JsonSerializerOptions Options = new() {
Converters = {
new JsonStringEnumConverter()
},
};
[TestMethod]
public void TestMethod1() {
var AsEnum = new DataItem<CustomEnum1>() {
Value = CustomEnum1.Item1,
};
var Text = JsonSerializer.Serialize(AsEnum);
Console.WriteLine(Text);
}
[TestMethod]
public void TestMethod2() {
var AsString = new DataItem<string>() {
Value = "Error",
};
var Text = JsonSerializer.Serialize(AsString);
var AsEnum = JsonSerializer.Deserialize<DataItem<CustomEnum1>>(Text, Options);
}
[TestMethod]
public void TestMethod3() {
var AsString = new DataItem<string>() {
Value = "Error",
};
var Text = JsonSerializer.Serialize(AsString);
var AsEnum = JsonSerializer.Deserialize<DataItem<CustomEnum2>>(Text);
}
}
public record DataItem<T> {
public T? Value { get; init; }
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum CustomEnum1 {
Item1,
Item2,
}
//From Macross.Json.Extensions NUGET PACKAGE
[JsonConverter(typeof(JsonStringEnumMemberConverter))]
public enum CustomEnum2 {
Item1,
Item2,
}
}
Expected behavior
A better error message is generated.
Actual behavior
An ambiguous error message is generated.
Regression?
No.
Known Workarounds
Use JsonStringEnumMemberConverter from the Macross.Json.Extensions nuget package.
Configuration
.NET 9.0
Latest VS Update
Other information
With the introduction of JsonStringEnumMemberName we want to switch from the Macross.Json.Extensions library but this error message change causes quite a pain point for us.