Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support SmartEnums as dictionary keys #458

Merged
merged 4 commits into from
Jan 16, 2024
Merged

Support SmartEnums as dictionary keys #458

merged 4 commits into from
Jan 16, 2024

Conversation

Steve-OH
Copy link
Contributor

@Steve-OH Steve-OH commented Nov 18, 2023

This addresses #242 by adding support for SmartEnums as dictionary keys when using System.Text.Json. It adds ReadAsPropertyName and WriteAsPropertyName implementations to both SmartEnumNameConverter and SmartEnumValueConverter.

Note that there isn't a good way to use the JsonConverter attribute when you want to use a dictionary with a SmartEnum as a key. Instead, you have to explicitly add the appropriate SmartEnum converter to the serializer options (see the tests for examples of this). While it would be possible to create a somewhat more generic dictionary converter that would allow you to use the JsonConverter attribute, there would have to be separate converter implementations for each of the different dictionary types (IDictionary, IImmutableDictionary, IList<KeyValuePair<TKey, TValue>>, etc.), which doesn't seem worth the effort.

A note on the value converter tests: There doesn't seem to be a way to create a C# anonymous object where the property name is not a valid identifier (e.g., you can't create an anonymous object that serializes to { "1.5": "foo" }, so I had to jump through a couple of small hoops to create the reference JSON for the (de)serialization tests.

@ardalis ardalis merged commit 447153b into ardalis:main Jan 16, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants