Skip to content

fix schema for nullable enums #3377

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

Merged
merged 2 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ public DataContract GetDataContractForType(Type type)
jsonConverter: JsonConverterFunc);
}

var jsonContract = _contractResolver.ResolveContract(effectiveType);
var jsonContract = _contractResolver.ResolveContract(type);

if (jsonContract is JsonPrimitiveContract && !jsonContract.UnderlyingType.IsEnum)
var effectiveUnderlyingType = Nullable.GetUnderlyingType(jsonContract.UnderlyingType) ?? jsonContract.UnderlyingType;

if (jsonContract is JsonPrimitiveContract && !effectiveUnderlyingType.IsEnum)
{
if (!PrimitiveTypesAndFormats.TryGetValue(jsonContract.UnderlyingType, out var primitiveTypeAndFormat))
if (!PrimitiveTypesAndFormats.TryGetValue(effectiveUnderlyingType, out var primitiveTypeAndFormat))
{
primitiveTypeAndFormat = Tuple.Create(DataType.String, (string)null);
}
Expand All @@ -38,9 +40,9 @@ public DataContract GetDataContractForType(Type type)
jsonConverter: JsonConverterFunc);
}

if (jsonContract is JsonPrimitiveContract && jsonContract.UnderlyingType.IsEnum)
if (jsonContract is JsonPrimitiveContract && effectiveUnderlyingType.IsEnum)
{
var enumValues = jsonContract.UnderlyingType.GetEnumValues();
var enumValues = effectiveUnderlyingType.GetEnumValues();

// Test to determine if the serializer will treat as string
var serializeAsString = (enumValues.Length > 0) &&
Expand All @@ -52,7 +54,7 @@ public DataContract GetDataContractForType(Type type)

var primitiveTypeAndFormat = serializeAsString
? PrimitiveTypesAndFormats[typeof(string)]
: PrimitiveTypesAndFormats[jsonContract.UnderlyingType.GetEnumUnderlyingType()];
: PrimitiveTypesAndFormats[effectiveUnderlyingType.GetEnumUnderlyingType()];

return DataContract.ForPrimitive(
underlyingType: jsonContract.UnderlyingType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public DataContract GetDataContractForType(Type type)
primitiveTypeAndFormat = PrimitiveTypesAndFormats[exampleType];

return DataContract.ForPrimitive(
underlyingType: effectiveType,
underlyingType: type,
dataType: primitiveTypeAndFormat.Item1,
dataFormat: primitiveTypeAndFormat.Item2,
jsonConverter: (value) => JsonConverterFunc(value, type));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ private OpenApiSchema GenerateSchemaForMember(
MemberInfo memberInfo,
DataProperty dataProperty = null)
{
if (dataProperty != null)
{
var customAttributes = memberInfo.GetInlineAndMetadataAttributes();

var requiredAttribute = customAttributes.OfType<RequiredAttribute>().FirstOrDefault();

if (!IsNullable(customAttributes, requiredAttribute, dataProperty, memberInfo))
{
modelType = Nullable.GetUnderlyingType(modelType) ?? modelType;
}
}

var dataContract = GetDataContractFor(modelType);

var schema = _generatorOptions.UseOneOfForPolymorphism && IsBaseTypeWithKnownTypesDefined(dataContract, out var knownTypesDataContracts)
Expand All @@ -75,11 +87,7 @@ private OpenApiSchema GenerateSchemaForMember(
{
var requiredAttribute = customAttributes.OfType<RequiredAttribute>().FirstOrDefault();

var nullable = _generatorOptions.SupportNonNullableReferenceTypes
? dataProperty.IsNullable && requiredAttribute == null && !memberInfo.IsNonNullableReferenceType()
: dataProperty.IsNullable && requiredAttribute == null;

schema.Nullable = nullable;
schema.Nullable = IsNullable(customAttributes, requiredAttribute, dataProperty, memberInfo);

schema.ReadOnly = dataProperty.IsReadOnly;
schema.WriteOnly = dataProperty.IsWriteOnly;
Expand Down Expand Up @@ -129,6 +137,13 @@ private OpenApiSchema GenerateSchemaForMember(
return schema;
}

private bool IsNullable(IEnumerable<object> customAttributes, RequiredAttribute requiredAttribute, DataProperty dataProperty, MemberInfo memberInfo)
{
return _generatorOptions.SupportNonNullableReferenceTypes
? dataProperty.IsNullable && requiredAttribute == null && !memberInfo.IsNonNullableReferenceType()
: dataProperty.IsNullable && requiredAttribute == null;
}

private OpenApiSchema GenerateSchemaForParameter(
Type modelType,
SchemaRepository schemaRepository,
Expand Down Expand Up @@ -264,7 +279,7 @@ private OpenApiSchema GenerateConcreteSchema(DataContract dataContract, SchemaRe
case DataType.String:
{
schemaFactory = () => CreatePrimitiveSchema(dataContract);
returnAsReference = dataContract.UnderlyingType.IsEnum && !_generatorOptions.UseInlineDefinitionsForEnums;
returnAsReference = (Nullable.GetUnderlyingType(dataContract.UnderlyingType) ?? dataContract.UnderlyingType).IsEnum && !_generatorOptions.UseInlineDefinitionsForEnums;
break;
}

Expand Down Expand Up @@ -330,10 +345,19 @@ private static OpenApiSchema CreatePrimitiveSchema(DataContract dataContract)
}
#pragma warning restore CS0618 // Type or member is obsolete

if (dataContract.UnderlyingType.IsEnum)
var underlyingType = Nullable.GetUnderlyingType(dataContract.UnderlyingType) ?? dataContract.UnderlyingType;

if (underlyingType.IsEnum)
{
schema.Enum = [.. dataContract.UnderlyingType.GetEnumValues()
.Cast<object>()
var enumValues = underlyingType.GetEnumValues().Cast<object>();

if (dataContract.UnderlyingType != underlyingType)
{
schema.Nullable = true;
enumValues = enumValues.Append(null);
}

schema.Enum = [.. enumValues
.Select(value => dataContract.JsonConverter(value))
.Distinct()
.Select(JsonModelFactory.CreateFromJson)];
Expand Down Expand Up @@ -440,9 +464,11 @@ private OpenApiSchema CreateObjectSchema(DataContract dataContract, SchemaReposi
continue;
}

var memberType = dataProperty.IsNullable ? dataProperty.MemberType : (Nullable.GetUnderlyingType(dataProperty.MemberType) ?? dataProperty.MemberType);

schema.Properties[dataProperty.Name] = (dataProperty.MemberInfo != null)
? GenerateSchemaForMember(dataProperty.MemberType, schemaRepository, dataProperty.MemberInfo, dataProperty)
: GenerateSchemaForType(dataProperty.MemberType, schemaRepository);
? GenerateSchemaForMember(memberType, schemaRepository, dataProperty.MemberInfo, dataProperty)
: GenerateSchemaForType(memberType, schemaRepository);

var markNonNullableTypeAsRequired =
_generatorOptions.NonNullableReferenceTypesAsRequired &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,7 @@ apiParameter.Type is not null &&

var schema = (type != null)
? GenerateSchema(
type,
isRequired ? (Nullable.GetUnderlyingType(type) ?? type) : type,
schemaRepository,
apiParameter.PropertyInfo(),
apiParameter.ParameterInfo(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1491,7 +1491,7 @@
"$ref": "#/components/schemas/ProductStatus"
},
"status2": {
"$ref": "#/components/schemas/ProductStatus"
"$ref": "#/components/schemas/ProductStatusNullable"
}
},
"additionalProperties": false,
Expand All @@ -1511,6 +1511,17 @@
"type": "integer",
"format": "int32"
},
"ProductStatusNullable": {
"enum": [
0,
1,
2,
null
],
"type": "integer",
"format": "int32",
"nullable": true
},
"Promotion": {
"type": "object",
"properties": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1491,7 +1491,7 @@
"$ref": "#/components/schemas/ProductStatus"
},
"status2": {
"$ref": "#/components/schemas/ProductStatus"
"$ref": "#/components/schemas/ProductStatusNullable"
}
},
"additionalProperties": false,
Expand All @@ -1511,6 +1511,17 @@
"type": "integer",
"format": "int32"
},
"ProductStatusNullable": {
"enum": [
0,
1,
2,
null
],
"type": "integer",
"format": "int32",
"nullable": true
},
"Promotion": {
"type": "object",
"properties": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,33 @@
{
"name": "logLevel",
"in": "query",
"schema": {
"allOf": [
{
"$ref": "#/components/schemas/LogLevelNullable"
}
],
"default": 4
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/RequiredEnum": {
"get": {
"tags": [
"RequiredEnum"
],
"parameters": [
{
"name": "logLevel",
"in": "query",
"required": true,
"schema": {
"allOf": [
{
Expand Down Expand Up @@ -46,6 +73,21 @@
],
"type": "integer",
"format": "int32"
},
"LogLevelNullable": {
"enum": [
0,
1,
2,
3,
4,
5,
6,
null
],
"type": "integer",
"format": "int32",
"nullable": true
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,33 @@
{
"name": "logLevel",
"in": "query",
"schema": {
"allOf": [
{
"$ref": "#/components/schemas/LogLevelNullable"
}
],
"default": 4
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
},
"/api/RequiredEnum": {
"get": {
"tags": [
"RequiredEnum"
],
"parameters": [
{
"name": "logLevel",
"in": "query",
"required": true,
"schema": {
"allOf": [
{
Expand Down Expand Up @@ -46,6 +73,21 @@
],
"type": "integer",
"format": "int32"
},
"LogLevelNullable": {
"enum": [
0,
1,
2,
3,
4,
5,
6,
null
],
"type": "integer",
"format": "int32",
"nullable": true
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@
"name": "paramNine",
"in": "query",
"schema": {
"$ref": "#/components/schemas/DateTimeKind"
"$ref": "#/components/schemas/DateTimeKindNullable"
}
},
{
Expand Down Expand Up @@ -946,7 +946,7 @@
"format": "time"
},
"paramNine": {
"$ref": "#/components/schemas/DateTimeKind"
"$ref": "#/components/schemas/DateTimeKindNullable"
},
"paramTen": {
"$ref": "#/components/schemas/DateTimeKind"
Expand Down Expand Up @@ -995,6 +995,17 @@
"type": "integer",
"format": "int32"
},
"DateTimeKindNullable": {
"enum": [
0,
1,
2,
null
],
"type": "integer",
"format": "int32",
"nullable": true
},
"Fruit": {
"type": "object",
"properties": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@
"name": "paramNine",
"in": "query",
"schema": {
"$ref": "#/components/schemas/DateTimeKind"
"$ref": "#/components/schemas/DateTimeKindNullable"
}
},
{
Expand Down Expand Up @@ -946,7 +946,7 @@
"format": "time"
},
"paramNine": {
"$ref": "#/components/schemas/DateTimeKind"
"$ref": "#/components/schemas/DateTimeKindNullable"
},
"paramTen": {
"$ref": "#/components/schemas/DateTimeKind"
Expand Down Expand Up @@ -995,6 +995,17 @@
"type": "integer",
"format": "int32"
},
"DateTimeKindNullable": {
"enum": [
0,
1,
2,
null
],
"type": "integer",
"format": "int32",
"nullable": true
},
"Fruit": {
"type": "object",
"properties": {
Expand Down
Loading