Skip to content

System.Text.Json: JsonStringEnumConverter ignores its JsonNamingPolicy during deserialization. #31619

Closed

Description

@dbc2

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

  1. added
    untriaged
    on Feb 2, 2020
  2. NoneGiven commented on Feb 2, 2020

    @NoneGiven

    #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.

  3. added this to the 5.0 milestone on Feb 2, 2020
  4. added and removed
    untriaged
    on Feb 2, 2020
  5. CodeBlanch commented on Feb 3, 2020

    @CodeBlanch
    Contributor

    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.

  6. Bukran commented on Mar 24, 2020

    @Bukran

    JsonStringEnumMemberConverter

    Thanks a lot! I was stumbling against deserialization.

  7. added
    help wanted
    on Apr 14, 2020
  8. Macromullet commented on Apr 15, 2020

    @Macromullet
    Contributor

    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.

  9. removed
    help wanted
    on May 8, 2020
  10. modified the milestones: 5.0.0, Future on Jul 7, 2020
  11. layomia commented on Aug 26, 2020

    @layomia
    Contributor

    from @liul in #41138:

    Use the obtained string value directly here. But why not use _namingPolicy'?

    like:

            internal override T ReadWithQuotes(ref Utf8JsonReader reader)
            {
                string? enumString = reader.GetString();
                
                var v =  _namingPolicy == null ? enumString : FormatEnumValueToString(enumString, encoder);
                 
                // Try parsing case sensitive first
                if (!Enum.TryParse(v, out T value)
                    && !Enum.TryParse(v, ignoreCase: true, out value))
                {
                    ThrowHelper.ThrowJsonException();
                }
    
                return value;
            }
  12. 2m0nd commented on Sep 15, 2020

    @2m0nd

    Maybe create cache with source enum value names? And restore source name if exist namingPolicy?
    #42302

  13. 20 remaining items

  14. modified the milestones: Future, 7.0.0 on Oct 25, 2021
  15. sabitkondakci commented on Nov 7, 2021

    @sabitkondakci

    @layomia I am assuming there is a 0% chance of a fix for this making it into .NET 6. Is that assumption correct?

    Will this feature be in .Net6 sooner or later?

  16. eiriktsarpalis commented on Nov 8, 2021

    @eiriktsarpalis
    Member

    Will this feature be in .Net6 sooner or later?

    We didn't get around to fixing this in time for .NET 6. It will be considered for .NET 7.

  17. brianlagunas commented on Jun 23, 2022

    @brianlagunas

    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.

  18. modified the milestones: 7.0.0, Future on Jul 10, 2022
  19. ghost added
    in-pr
    on Aug 4, 2022
  20. modified the milestones: Future, 7.0.0 on Aug 5, 2022
  21. ghost removed
    in-pr
    on Aug 11, 2022
  22. ghost locked as resolved and limited conversation to collaborators on Sep 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions