Skip to content

Commit

Permalink
Support [JsonRequired] (#2988)
Browse files Browse the repository at this point in the history
Mark properties as required if annotated with `[JsonRequired]` for System.Text.Json.
  • Loading branch information
jgarciadelanoceda authored Jul 18, 2024
1 parent fdb7d6b commit 3553751
Show file tree
Hide file tree
Showing 6 changed files with 176 additions and 3 deletions.
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,28 @@
},
"additionalProperties": false
},
"CurrenciesRate": {
"required": [
"currencyFrom",
"currencyTo"
],
"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 +516,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,28 @@
},
"additionalProperties": false
},
"CurrenciesRate": {
"required": [
"currencyFrom",
"currencyTo"
],
"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 +516,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());
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, double Rate);
}

0 comments on commit 3553751

Please sign in to comment.