Enums

Rico Suter edited this page Jun 19, 2018 · 15 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).

Also see Integer vs String enumerations

Globally enable string enum serialization in ASP.NET Core

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

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.

JsonSchemaGenerator:

  • Generates the custom extension x-flagEnum (property JsonSchema4.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: See #719

PR: https://github.com/RSuter/NJsonSchema/pull/713