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

EnumMember attribute ignored by StringEnumConvertor if CamelCaseText = true #2082

Closed
wizofaus opened this issue Jun 3, 2019 · 4 comments · Fixed by #2186
Closed

EnumMember attribute ignored by StringEnumConvertor if CamelCaseText = true #2082

wizofaus opened this issue Jun 3, 2019 · 4 comments · Fixed by #2186

Comments

@wizofaus
Copy link

wizofaus commented Jun 3, 2019

Using

new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = new[] { new StringEnumConverter { CamelCaseText = true } }
        }

I get enum values converted to "camelCase" strings as expected, even though the actual enum fields in the C# definition are PascalCase.

But in some cases I need to override the default name, and normally [EnumMember(Value="UPPER_CASE_NAME")] does the trick - but not when CamelCaseText is true.
As such I wrote my own resolver that overrides WriteJson and checks for the attribute itself, but is this really the expected behaviour, and if so, is there a case for having a way of overriding it?

@wizofaus
Copy link
Author

wizofaus commented Sep 30, 2019

BTW I've confirmed this problem is still in the latest version of Json.NET - even though CamelCaseNamingStrategy has a property "OverrideSpecifiedNames" which can be set via the constructor (and defaults to false), it completely ignores this property when resolving, so my field value with [EnumMember(Value="UPPER_CASE_NAME")] gets written as uPPER_CASE_NAME.

The bug appears to be in EnumUtils.InitializeValuesAndNames - it always passes false to NamingStrategy.GetPropertyName( ), regardless of the EnumMember annotation.

See https://github.com/JamesNK/Newtonsoft.Json/blob/cdf10151d507d497a3f9a71d36d544b199f73435/Src/Newtonsoft.Json/Utilities/EnumUtils.cs/#LC51

@JamesNK
Copy link
Owner

JamesNK commented Oct 5, 2019

Thanks for the investigation. Fixed.

@wizofaus
Copy link
Author

wizofaus commented Oct 7, 2019

Gotta love github :-)

Though...I do wonder if there's any chance the functionality in EnumUtils.TryToString( ) could be made public? Need to use it for customizing swagger output (e.g. list of possible enum values)

@bartelink
Copy link

You could just clone it? what happens if you change to a different serializer?

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 a pull request may close this issue.

3 participants