-
-
Notifications
You must be signed in to change notification settings - Fork 528
Enums
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).
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.Converters.Add(new StringEnumConverter()));
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.
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"],
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).
- Generates the custom extension
x-enumFlags
(propertyJsonSchema.IsFlagEnumeration
) for enums with the[Flags]
attribute (boolean, default: false)
- Generates DTOs with [Flags] attribute when the setting
EnforceFlagEnums
orx-enumFlags
is set totrue
This feature is currently not supported in the TypeScriptGenerator, for more information see #719