Skip to content

System.Text.Json 9.0 can break case-insensitive enum deserialization when there is a naming policy #110745

Closed
@atykhyy

Description

@atykhyy

Description

System.Text.Json 9.0.0 no longer deserializes strings to enums in a case-insensitive manner when there is a naming policy that does not change the case of the enum's string representation (see example below; a do-nothing naming policy which returns the original name also has this problem).

Reproduction Steps

The following example can be run in .NET Fiddle. It works when compiler is set to .NET 8 (which imports STJ 8.x), and fails when compiler is set to .NET 9.

using System;
using System.Text.Json;
using System.Text.Json.Serialization;
					
public class Program
{
  public static void Main()
  {
    var options = new JsonSerializerOptions () ;
    options.Converters.Add (new JsonStringEnumConverter (JsonNamingPolicy.SnakeCaseUpper)) ; // needs to preserve casing of Foo.A
    // works with System.Text.Json 8.x, throws with System.Text.Json 9.0.0
    Console.WriteLine (JsonSerializer.Deserialize<Foo> ("\"a\"", options)) ;
  }
}

enum Foo
{
  A = 1,
}

Expected behavior

In System.Text.Json 8.x and earlier, strings could always be deserialized to enum in a case-insensitive manner regardless of naming policy.

Actual behavior

Upgrading System.Text.Json to 9.0.0 silently breaks existing code as enums in lower case can no longer be deserialized.

Regression?

This regression was introduced by the rewrite of EnumConverter.cs in #105032 (commit 78db74f). The same user code works with System.Text.Json 8.x and earlier.

Known Workarounds

From my reading of EnumConverter.cs, no workaround with the existing System.Text.Json enum converter is possible. One would have to create a custom converter for enums and use it in place of JsonStringEnumConverter, or replace the enum converter factory and change internal fields of each enum converter with reflection after the converter is created.

Configuration

.NET 8

Other information

No response

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions