Skip to content
Rico Suter edited this page Jun 24, 2019 · 26 revisions

The enums in JSON Schema are only used to validate JSON data. This is why you can only define the enum values but not their names. NJsonSchema adds the x-enumNames property to the schema so that the enum value names are also available to the consumer. These names are required to generate meaningful code (CSharp or TypeScript).

Globally enable string enum serialization in ASP.NET Core

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddJsonOptions(options => 
            options.SerializerSettings.Converters.Add(new StringEnumConverter()));

Integer vs string enumerations

JSON Schema supports integer and string enumerations. In Json.NET, enums are serialized as integer by default. However you can mark a property with the JsonConverterAttribute so that it is serialized as string. NJsonSchema looks for these attributes and generates the enum JSON Schema respecting this attribute:

// Only this property is serialized as string
[JsonConverter(typeof(StringEnumConverter))]
public Gender Gender { get; set; }

// Always serialized as string
[JsonConverter(typeof(StringEnumConverter))]
public enum Gender
{
    ...
}

Because integer enums cannot preserve the original enum names, we added the setting GenerateEnumMappingDescription which preserves the names in the summary field.

Enum names and descriptions

The JSON Schema's enum property only contains a list of values (which are transferred over the wire) and cannot describe the names of the values. This is why this library introduces another custom property x-enumNames: This property always holds the original enum name (e.g. Male instead of 5). To change the serialized value use the EnumMemberAttribute:

[JsonConverter(typeof(StringEnumConverter))]
public enum Gender
{
    [EnumMember(Value = "male")]
    Male = 5, 
    [EnumMember(Value = "female")]
    Female = 8,
}

This would generate the following enum in JSON Schema:

"x-enumNames": ["Male", "Female"],
"enum": ["male", "female"],

Flags enums

NJsonSchema supports flags enums. Because this feature is not natively supported in JSON Schema, and custom extension properties are required, we recommend to avoid flags enums and use enum arrays instead (PR: #713).

JsonSchemaGenerator:

  • Generates the custom extension x-flagEnum (property JsonSchema.IsFlagEnumeration) for enums with the [Flags] attribute (boolean, default: false)

CSharpGenerator:

  • Generates DTOs with [Flags] attribute when the setting EnforceFlagEnums or x-flagEnum is set to true

This feature is currently not supported in the TypeScriptGenerator, for more information see #719

TODO: Update wiki with explanation here: https://github.com/RSuter/NSwag/issues/1234#issuecomment-470519135

Clone this wiki locally