Skip to content
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

Take into account JsonRequired of STJ #2988

Merged
Show file tree
Hide file tree
Changes from 3 commits
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 @@ -210,11 +210,13 @@ private List<DataProperty> GetDataPropertiesFor(Type objectType, out Type extens
// See https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-immutability?pivots=dotnet-6-0
var isDeserializedViaConstructor = false;

var isRequired = false;

#if NET5_0_OR_GREATER
var deserializationConstructor = propertyInfo.DeclaringType?.GetConstructors()
.OrderBy(c =>
{
if (c.GetCustomAttribute<System.Text.Json.Serialization.JsonConstructorAttribute>() != null) return 1;
if (c.GetCustomAttribute<JsonConstructorAttribute>() != null) return 1;
if (c.GetParameters().Length == 0) return 2;
return 3;
})
Expand All @@ -228,11 +230,14 @@ private List<DataProperty> GetDataPropertiesFor(Type objectType, out Type extens
string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase);
});
#endif
#if NET7_0_OR_GREATER
isRequired = propertyInfo.GetCustomAttribute<JsonRequiredAttribute>() != null;
#endif

dataProperties.Add(
new DataProperty(
name: name,
isRequired: false,
isRequired: isRequired,
isNullable: propertyInfo.PropertyType.IsReferenceOrNullableType(),
isReadOnly: propertyInfo.IsPubliclyReadable() && !propertyInfo.IsPubliclyWritable() && !isDeserializedViaConstructor,
isWriteOnly: propertyInfo.IsPubliclyWritable() && !propertyInfo.IsPubliclyReadable(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,35 @@
}
}
},
"/WithOpenApi/IFromBody": {
"post": {
"tags": [
"WithOpenApi"
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/OrganizationCustomExchangeRatesDto"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/XmlComments/Car/{id}": {
"get": {
"tags": [
Expand Down Expand Up @@ -445,6 +474,29 @@
},
"additionalProperties": false
},
"CurrenciesRate": {
"required": [
"currencyFrom",
"currencyTo",
"rate"
],
"type": "object",
"properties": {
"currencyFrom": {
"type": "string",
"nullable": true
},
"currencyTo": {
"type": "string",
"nullable": true
},
"rate": {
"type": "number",
"format": "double"
}
},
"additionalProperties": false
},
"DateTimeKind": {
"enum": [
0,
Expand All @@ -465,6 +517,22 @@
"additionalProperties": false,
"description": "Description for Schema"
},
"OrganizationCustomExchangeRatesDto": {
"required": [
"currenciesRates"
],
"type": "object",
"properties": {
"currenciesRates": {
"type": "array",
"items": {
"$ref": "#/components/schemas/CurrenciesRate"
},
"nullable": true
}
},
"additionalProperties": false
},
"Person": {
"type": "object",
"properties": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,35 @@
}
}
},
"/WithOpenApi/IFromBody": {
"post": {
"tags": [
"WithOpenApi"
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/OrganizationCustomExchangeRatesDto"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/XmlComments/Car/{id}": {
"get": {
"tags": [
Expand Down Expand Up @@ -445,6 +474,29 @@
},
"additionalProperties": false
},
"CurrenciesRate": {
"required": [
"currencyFrom",
"currencyTo",
"rate"
],
"type": "object",
"properties": {
"currencyFrom": {
"type": "string",
"nullable": true
},
"currencyTo": {
"type": "string",
"nullable": true
},
"rate": {
"type": "number",
"format": "double"
}
},
"additionalProperties": false
},
"DateTimeKind": {
"enum": [
0,
Expand All @@ -465,6 +517,22 @@
"additionalProperties": false,
"description": "Description for Schema"
},
"OrganizationCustomExchangeRatesDto": {
"required": [
"currenciesRates"
],
"type": "object",
"properties": {
"currenciesRates": {
"type": "array",
"items": {
"$ref": "#/components/schemas/CurrenciesRate"
},
"nullable": true
}
},
"additionalProperties": false
},
"Person": {
"type": "object",
"properties": {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Text.Json.Serialization;

namespace Swashbuckle.AspNetCore.SwaggerGen.Test.Fixtures;

internal class JsonRequiredAnnotatedType
{

#if NET7_0_OR_GREATER
[JsonRequired]
#endif
public string StringWithJsonRequired { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,20 @@ public void GenerateSchema_HonorsSerializerAttribute_JsonPropertyName()
Assert.Equal(new[] { "string-with-json-property-name" }, schema.Properties.Keys.ToArray());
}

#if NET7_0_OR_GREATER
[Fact]
public void GenerateSchema_HonorsSerializerAttribute_JsonRequired()
{
var schemaRepository = new SchemaRepository();

var referenceSchema = Subject().GenerateSchema(typeof(JsonRequiredAnnotatedType), schemaRepository);

var schema = schemaRepository.Schemas[referenceSchema.Reference.Id];
Assert.Equal(new[] { "StringWithJsonRequired" }, schema.Required.ToArray());
jgarciadelanoceda marked this conversation as resolved.
Show resolved Hide resolved
Assert.True(schema.Properties["StringWithJsonRequired"].Nullable);
}
#endif

[Fact]
public void GenerateSchema_HonorsSerializerAttribute_JsonExtensionData()
{
Expand Down
10 changes: 9 additions & 1 deletion test/WebSites/WebApi/EndPoints/OpenApiEndpoints.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;

namespace WebApi.EndPoints
{
Expand Down Expand Up @@ -51,6 +52,11 @@ public static IEndpointRouteBuilder MapWithOpenApiEndpoints(this IEndpointRouteB
return $"{collection.Count} {string.Join(',', collection.Select(f => f.FileName))}";
}).WithOpenApi();

group.MapPost("/IFromBody", (OrganizationCustomExchangeRatesDto dto) =>
{
return $"{dto}";
}).WithOpenApi();

return app;
}
}
Expand All @@ -61,4 +67,6 @@ record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
record class Person(string FirstName, string LastName);

record class Address(string Street, string City, string State, string ZipCode);
sealed record OrganizationCustomExchangeRatesDto([property: JsonRequired] CurrenciesRate[] CurrenciesRates);
sealed record CurrenciesRate([property: JsonRequired] string currencyFrom, [property: JsonRequired] string currencyTo, [property: JsonRequired] double rate);
jgarciadelanoceda marked this conversation as resolved.
Show resolved Hide resolved
}