Repository navigation
Description
In System.Text.Json in .Net Core 3.1, I can serialize an enum using a naming policy, however when I attempt to deserialize the same enum with a naming policy, the policy is ignored and an exception is thrown when the naming policy does anything beyond modifying the case of the enum value names.
The issue can be reproduced as follows. Define the following simple snake case naming policy:
public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
return string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + Char.ToLowerInvariant(x).ToString() : Char.ToLowerInvariant(x).ToString()));
}
}
And the following enum:
public enum TestEnum
{
ValueZero,
ValueOne,
ValueTwo,
ValueThree
}
Then attempting to round-trip values of TestEnum will fail during deserialization:
var values = (TestEnum [])Enum.GetValues(typeof(TestEnum));
var options = new JsonSerializerOptions
{
Converters = { new JsonStringEnumConverter(new SnakeCaseNamingPolicy()) },
WriteIndented = true,
};
var json = JsonSerializer.Serialize(values, options);
Console.WriteLine("Serialized {0}:", values);
Console.WriteLine(json);
var valuesIn = JsonSerializer.Deserialize<TestEnum []>(json, options); // Exception thrown here!
Assert.IsTrue(valuesIn.SequenceEqual(values));
The enum values are serialized with the naming policy successfully:
[
"value_zero",
"value_one",
"value_two",
"value_three"
]
But deserialization throws this exception:
Failed with unhandled exception:
System.Text.Json.JsonException: The JSON value could not be converted to TestEnum[]. Path: $[0] | LineNumber: 1 | BytePositionInLine: 14.
at System.Text.Json.ThrowHelper.ThrowJsonException()
at System.Text.Json.Serialization.Converters.JsonConverterEnum`1.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.JsonPropertyInfoNotNullable`4.OnReadEnumerable(ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.JsonPropertyInfo.ReadEnumerable(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
The problem seems to be that JsonConverterEnum<T>.Read() completely ignores the specified _namingPolicy and simply calls Enum.TryParse():
// Try parsing case sensitive first
string? enumString = reader.GetString();
if (!Enum.TryParse(enumString, out T value)
&& !Enum.TryParse(enumString, ignoreCase: true, out value))
{
ThrowHelper.ThrowJsonException();
return default;
}
return value;
A close reading of the documentation here seems to imply that this is an intended limitation:
Reading is case insensitive. Writing can be customized by using a JsonNamingPolicy.
However the inconsistency and inability to round-trip with the same settings is an odd and unexpected restriction. Newtonsoft does not have this limitation -- it can round-trip enum values even when using SnakeCaseNamingStrategy.
Demo fiddle here showing that Json.NET can round-trip enums using SnakeCaseNamingStrategy while System.Text.Json cannot do so with SnakeCaseNamingPolicy.
Activity
NoneGiven commentedon Feb 2, 2020
#1197 is related in that it concerns questionable assumptions about naming policy made by these predefined converters. Of note, if #782 (which is
api-approved) is implemented, then this issue will become a bug when using a built-in naming policy rather than just a custom one.CodeBlanch commentedon Feb 3, 2020
Anyone looking for a workaround I have a JsonConverter named JsonStringEnumMemberConverter in Macross.Json.Extensions package which fixes this issue and then adds in support for EnumMemberAttribute & Nullable enums. A modified version of dotnet/corefx#41648, basically.
Bukran commentedon Mar 24, 2020
Thanks a lot! I was stumbling against deserialization.
Macromullet commentedon Apr 15, 2020
I don't see how this can be addressed with the current API shape, as JsonNamingPolicy.ConvertName is potentially a one-way function. For instance, if you chose HashFunction(name) as the implementation, it's not possible to convert it back. The only way to support this would be to define something like WPF does with converters, where you have Convert and ConvertBack, but that seems to be functionality outside the scope of what System.Text.Json should do.
layomia commentedon Aug 26, 2020
from @liul in #41138:
2m0nd commentedon Sep 15, 2020
Maybe create cache with source enum value names? And restore source name if exist namingPolicy?
#42302
20 remaining items
sabitkondakci commentedon Nov 7, 2021
Will this feature be in .Net6 sooner or later?
eiriktsarpalis commentedon Nov 8, 2021
We didn't get around to fixing this in time for .NET 6. It will be considered for .NET 7.
Modernize project and target .NET Standard 2.0
brianlagunas commentedon Jun 23, 2022
I also need this functionality. Seems silly to me that a naming policy would only apply on serialization and not deserialization. Seems like a massive oversight.
Please fix this.