Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snake Cased names for enum values

Tags:

c#

json.net

Is there any built in functionality in Newtonsoft.Json for serializing enum values into their snake-cased names?

currently, I am providing values manually:

[JsonConverter(typeof(StringEnumConverter))]
enum MyEnum {
    [EnumMember(Value = "value_one")]
    ValueOne,
}
like image 389
Poulad Avatar asked Jan 04 '18 13:01

Poulad


People also ask

How do you name an enum?

Enums are types, so they should be named using UpperCamelCase like classes. The enum values are constants, so they should be named using lowerCamelCase like constants, or ALL_CAPS if your code uses that legacy naming style.

Should enums be capitalized typescript?

Use uppercase letters for your enums - they are global constants which have usable values. They are more than just types, which use usually like Foo or TFoo . The keys on an enum tend to be titlecase.

Can we use underscore in enum?

Since enum fields are constants, java best practice is to write them in block letters and underscore for spaces. For example EAST, WEST, EAST_DIRECTION etc. Enum constants are final but it's variable can still be changed.

What are enum types?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.


1 Answers

Optional snake-casing of enum values has been implemented in Json.NET 12.0.1. It is now possible to specify a NamingStrategy for StringEnumConverter:

New feature - Added support for NamingStrategy to StringEnumConverter

Thus you can pass SnakeCaseNamingStrategy into any of several of the constructors for StringEnumConverter, e.g. new StringEnumConverter(typeof(SnakeCaseNamingStrategy)).

Using this, you can now specify that enums should be snake-cased globally when serialized by adding an appropriate converter to JsonSerializerSettings.Converters:

var settings = new JsonSerializerSettings
{
    Converters = { new StringEnumConverter(typeof(SnakeCaseNamingStrategy)) },
};
var json = JsonConvert.SerializeObject(MyEnum.ValueOne, settings);

Assert.IsTrue(json == "\"value_one\""); // Passes successfully

Or, alternatively, SnakeCaseNamingStrategy can be applied to select enums as follows:

[JsonConverter(typeof(StringEnumConverter), typeof(SnakeCaseNamingStrategy))]
enum MyEnum
{
    ValueOne,
    // Other values...
}

For further information see Issue #1862: [Feature] StringEnumConverter takes a NamingStrategy argument.

like image 76
dbc Avatar answered Oct 28 '22 02:10

dbc