Skip to content

[Bug]: Enum dictionary keys not supported by the default Refit settings, CamelCaseStringEnumConverter throws an exception #2111

Description

@Kloizdena

Describe the bug 🐞

When I try to send or receive a dictionary with an enum key with the default Refit settings, it throws an exception because the JsonSerializer added to the default Refit settings does not override the ReadAsPropertyName and WriteAsPropertyName methods.

Step to reproduce

Run the following code as a Console app:

using System.Text.Json;

var jsonOptions = Refit.SystemTextJsonContentSerializer.GetDefaultJsonSerializerOptions();
var dictionary = new Dictionary<MyEnum, string>
{
    [MyEnum.FirstValue] = "a",
    [MyEnum.SecondValue] = "b",
};
// Fails with StackOverflowException
_ = JsonSerializer.Serialize(dictionary, jsonOptions);

// Fails with System.NotSupportedException:
// 'The type 'System.Object' is not a supported dictionary key using converter of type 'System.Text.Json.Serialization.Converters.DefaultObjectConverter'.
// Custom converters can add support for dictionary key serialization by overriding the 'ReadAsPropertyName' and 'WriteAsPropertyName' methods.
_ = JsonSerializer.Deserialize<Dictionary<MyEnum, string>>(@"{""FirstValue"": ""a""}", jsonOptions);

public enum MyEnum
{
    FirstValue,
    SecondValue,
}

csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
	<ItemGroup>
		<PackageReference Include="Refit" Version="10.1.6" />
	</ItemGroup>
</Project>

Reproduction repository

https://github.com/reactiveui/refit

Expected behavior

The enum converter should support serializing enums as dictionary keys

Screenshots 🖼️

No response

IDE

No response

Operating system

No response

Version

No response

Device

No response

Refit Version

10.1.6

Additional information ℹ️

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    🐛 bug🔤 area: serializationJSON (STJ/Newtonsoft), content serializers, converters🟠 priority: mediumReal bug in a narrower scenario, or a commonly-requested feature

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions