├── images ├── NodaTime0.png ├── NodaTime1.png └── NodaTime2.png ├── samples └── WebApiSample │ ├── appsettings.json │ ├── appsettings.Development.json │ ├── Controllers │ ├── DefaultController.cs │ ├── NodaTimeModel.cs │ └── NodaTimeValuesController.cs │ ├── Program.cs │ ├── WebApiSample.csproj │ └── Startup.cs ├── version.props ├── test ├── Directory.Build.props └── MicroElements.Swashbuckle.NodaTime.Tests │ ├── MicroElements.Swashbuckle.NodaTime.Tests.csproj │ └── SchemasTests.cs ├── appveyor.yml ├── .config └── dotnet-tools.json ├── .travis.yml ├── MicroElements.Swashbuckle.NodaTime.sln.DotSettings ├── src ├── Directory.Build.props ├── stylecop.ruleset ├── stylecop.props ├── stylecop.json └── MicroElements.Swashbuckle.NodaTime │ ├── MicroElements.Swashbuckle.NodaTime.csproj │ ├── NamingPolicyParameterFilter.cs │ ├── GlobalSuppressions.cs │ ├── NodaTimeSchemaSettings.cs │ ├── Schemas.cs │ ├── SchemasFactory.cs │ ├── SchemaExamples.cs │ ├── NodaTimeSchemaSettingsFactory.cs │ └── SwaggerGenOptionsExtensions.cs ├── .vscode └── launch.json ├── LICENSE ├── common.props ├── CHANGELOG.md ├── MicroElements.Swashbuckle.NodaTime.sln ├── .gitignore ├── .editorconfig └── README.md /images/NodaTime0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/HEAD/images/NodaTime0.png -------------------------------------------------------------------------------- /images/NodaTime1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/HEAD/images/NodaTime1.png -------------------------------------------------------------------------------- /images/NodaTime2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/HEAD/images/NodaTime2.png -------------------------------------------------------------------------------- /samples/WebApiSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /version.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.1 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /test/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | image: Visual Studio 2017 2 | build_script: 3 | - ps: .\build.ps1 -Target AppVeyor 4 | test: off 5 | skip_commits: 6 | files: 7 | - '**/*.md' 8 | artifacts: 9 | - path: artifacts/packages/*.nupkg -------------------------------------------------------------------------------- /samples/WebApiSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "cake.tool": { 6 | "version": "0.38.0", 7 | "commands": [ 8 | "dotnet-cake" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: csharp 3 | mono: none 4 | dotnet: 3.1 5 | os: 6 | - linux 7 | before_script: 8 | - chmod a+x ./build.sh 9 | script: 10 | - ./build.sh --target=Travis --verbosity=normal --ForceUploadPackages=false 11 | -------------------------------------------------------------------------------- /samples/WebApiSample/Controllers/DefaultController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace WebApiSample.Controllers 4 | { 5 | [ApiExplorerSettings(IgnoreApi = true), Route("")] 6 | public class DefaultController : Controller 7 | { 8 | [HttpGet] 9 | public IActionResult Get() => Redirect("swagger"); 10 | } 11 | } -------------------------------------------------------------------------------- /MicroElements.Swashbuckle.NodaTime.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True -------------------------------------------------------------------------------- /samples/WebApiSample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace WebApiSample 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | WebHost 11 | .CreateDefaultBuilder(args) 12 | .UseStartup() 13 | .Build() 14 | .Run(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | embedded 7 | true 8 | true 9 | true 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/stylecop.ruleset: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/stylecop.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | $(MSBuildThisFileDirectory)stylecop.ruleset 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/stylecop.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", 3 | "settings": { 4 | "documentationRules": { 5 | "companyName": "MicroElements", 6 | "copyrightText": "Copyright (c) {companyName}. All rights reserved.\nLicensed under the {licenseName} license. See {licenseFile} file in the project root for full license information.", 7 | "variables": { 8 | "licenseName": "MIT", 9 | "licenseFile": "LICENSE" 10 | }, 11 | "xmlHeader": false 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/MicroElements.Swashbuckle.NodaTime.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netstandard2.0 6 | enable 7 | latest 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /samples/WebApiSample/WebApiSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /samples/WebApiSample/Controllers/NodaTimeModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using NodaTime; 3 | 4 | namespace WebApiSample.Controllers 5 | { 6 | public class NodaTimeModel 7 | { 8 | public DateTime DateTime { get; set; } 9 | 10 | public DateTimeZone DateTimeZone { get; set; } 11 | public Instant Instant { get; set; } 12 | public Interval Interval { get; set; } 13 | public DateInterval DateInterval { get; set; } 14 | public Period Period { get; set; } 15 | public ZonedDateTime ZonedDateTime { get; set; } 16 | public OffsetDateTime OffsetDateTime { get; set; } 17 | public LocalDate LocalDate { get; set; } 18 | public LocalTime LocalTime { get; set; } 19 | public LocalDateTime LocalDateTime { get; set; } 20 | public Offset Offset { get; set; } 21 | public Duration Duration { get; set; } 22 | public OffsetDate OffsetDate { get; set; } 23 | public OffsetTime OffsetTime { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/MicroElements.Swashbuckle.NodaTime.Tests/MicroElements.Swashbuckle.NodaTime.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Cake: Debug Script (CoreCLR)", 6 | "type": "coreclr", 7 | "request": "launch", 8 | "program": "${workspaceRoot}/tools/Cake.CoreCLR/0.29.0/Cake.dll", 9 | "args": [ 10 | //"${workspaceRoot}/build.cake", 11 | //uncomment and edit for component script debug 12 | "${workspaceRoot}/tools/microelements.devops/1.6.0/scripts/main.cake", 13 | "--devOpsRoot=${workspaceRoot}/tools/microelements.devops/1.6.0", 14 | "--debug", 15 | "--verbosity=diagnostic", 16 | "--rootDir=${workspaceRoot}", 17 | "--Target=Default", 18 | "--TestSourceLink=false", 19 | "--Header=\"-+++++++-,MicroElements,DevOps,-+++++++-\"" 20 | ], 21 | "cwd": "${workspaceRoot}", 22 | "stopAtEntry": true, 23 | "externalConsole": false 24 | } 25 | ], 26 | "compounds": [] 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 MicroElements 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /common.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | micro-elements 5 | 6 | Configure Asp.Net Core and swagger to use NodaTime types. 7 | 8 | # Benefits of MicroElements.Swashbuckle.NodaTime 9 | - Supports Swashbuckle 5, net core 3 and brand new System.Text.Json 10 | - Implemented in c#, no FSharp.Core lib in dependencies 11 | - NamingStrategy support. You can use DefaultNamingStrategy, CamelCaseNamingStrategy or SnakeCaseNamingStrategy 12 | - Supports DateInterval 13 | - Can be generated with user provided examples or without examples 14 | 15 | 16 | swagger swashbuckle NodaTime aspnetcore 17 | https://raw.githubusercontent.com/micro-elements/MicroElements/master/image/logo_rounded.png 18 | https://github.com/micro-elements/MicroElements.Swashbuckle.NodaTime 19 | https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/master/LICENSE 20 | git 21 | https://github.com/micro-elements/MicroElements.Swashbuckle.NodaTime 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/NamingPolicyParameterFilter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using Microsoft.OpenApi.Models; 5 | using Swashbuckle.AspNetCore.SwaggerGen; 6 | 7 | namespace MicroElements.Swashbuckle.NodaTime 8 | { 9 | /// 10 | /// Resolves property name by . 11 | /// 12 | internal class NamingPolicyParameterFilter : IParameterFilter 13 | { 14 | private readonly NodaTimeSchemaSettings _nodaTimeSchemaSettings; 15 | 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | /// Settings that controls serialization aspects. 20 | public NamingPolicyParameterFilter(NodaTimeSchemaSettings nodaTimeSchemaSettings) 21 | { 22 | _nodaTimeSchemaSettings = nodaTimeSchemaSettings; 23 | } 24 | 25 | /// 26 | public void Apply(OpenApiParameter parameter, ParameterFilterContext context) 27 | { 28 | parameter.Name = _nodaTimeSchemaSettings.ResolvePropertyName(parameter.Name); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /samples/WebApiSample/Controllers/NodaTimeValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Mvc; 3 | using NodaTime; 4 | 5 | namespace WebApiSample.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | public class NodaTimeValuesController : ControllerBase 10 | { 11 | [HttpGet("[action]")] 12 | public ActionResult GetModel() 13 | { 14 | var dateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); 15 | Instant instant = Instant.FromDateTimeUtc(DateTime.UtcNow); 16 | ZonedDateTime zonedDateTime = instant.InZone(dateTimeZone); 17 | NodaTimeModel nodaTimeModel = new NodaTimeModel 18 | { 19 | DateTimeZone = DateTimeZone.Utc, 20 | Instant = instant, 21 | DateTime = DateTime.UtcNow, 22 | Interval = new Interval(instant, instant.Plus(Duration.FromHours(1))), 23 | DateInterval = new DateInterval(zonedDateTime.Date, zonedDateTime.Date.PlusDays(1)), 24 | Period = Period.FromHours(1), 25 | ZonedDateTime = zonedDateTime, 26 | OffsetDateTime = instant.WithOffset(Offset.FromHours(1)), 27 | LocalDate = zonedDateTime.Date, 28 | LocalTime = zonedDateTime.TimeOfDay, 29 | LocalDateTime = zonedDateTime.LocalDateTime, 30 | Offset = zonedDateTime.Offset, 31 | Duration = Duration.FromHours(1), 32 | OffsetDate = new OffsetDate(zonedDateTime.Date, zonedDateTime.Offset), 33 | OffsetTime = new OffsetTime(zonedDateTime.TimeOfDay, zonedDateTime.Offset), 34 | }; 35 | return nodaTimeModel; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1200:Using directives should be placed correctly", Justification = "Reviewed.")] 5 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1309:Field names should not begin with underscore", Justification = "Reviewed.")] 6 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1101:Prefix local calls with this", Justification = "Reviewed.")] 7 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1116:Split parameters should start on line after declaration", Justification = "Reviewed.")] 8 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1413:Use trailing comma in multi-line initializers", Justification = "Reviewed.")] 9 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1008:Opening parenthesis should be spaced correctly", Justification = "Reviewed.")] 10 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1015:Closing generic brackets should be spaced correctly", Justification = "Reviewed.")] 11 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1025:Code should not contain multiple whitespace in a row", Justification = "Reviewed.")] 12 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.LayoutRules", "SA1503:Braces should not be omitted", Justification = "Reviewed.")] 13 | [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:Elements should appear in the correct order", Justification = "Reviewed.")] 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 4.0.0 2 | - NodaTime updated to 3.0.0 3 | - NodaTime.Serialization.JsonNet updated to 3.0.0 4 | - NodaTime.Serialization.SystemTextJson updated to 1.0.0 5 | - Swashbuckle.AspNetCore updated to version 5.5.1 6 | - Added SchemaExamples to NodaTimeSchemaSettings and configuration methods ConfigureForNodaTime and ConfigureForNodaTimeWithSystemTextJson to support custom example values 7 | - Nullable annotations added 8 | 9 | # 3.0.0 10 | - Supports Swashbuckle 5, net core 3 and System.Text.Json 11 | - Swashbuckle.AspNetCore updated to version 5.0.0 12 | - NodaTime and NodaTime.Serialization.JsonNet updated to latest versions 13 | - ConfigureForNodaTime became more customizable 14 | - Compatibility with System.Text.Json: 15 | - New dependency: NodaTime.Serialization.SystemTextJson 16 | - Added new ConfigureForNodaTimeWithSystemTextJson 17 | - PR #13 by jeremyhayes: remove unspecified format aliases (full-date, partial-time) 18 | - PR #8 by Romanx: Add flag for generating examples in output 19 | - PR #11 by dgarciarubio: Add support for OffsetDate and OffsetTime types 20 | 21 | # 3.0.0-rc.4 22 | - PR #8 by Romanx: Add flag for generating examples in output 23 | - PR #11 by dgarciarubio: Add support for OffsetDate and OffsetTime types 24 | 25 | # 3.0.0-rc.3 26 | - Supports Swashbuckle 5, net core 3 and System.Text.Json 27 | - Swashbuckle.AspNetCore updated to version 5.0.0 28 | 29 | # 3.0.0-rc.2 30 | - Supports net core 3 and brand new System.Text.Json 31 | - NodaTime and NodaTime.Serialization.JsonNet updated to latest versions 32 | - Swashbuckle.AspNetCore updated to version 5.0.0-rc5 33 | - ConfigureForNodaTime became more customizable 34 | - Compatibility with System.Text.Json: 35 | - New dependency: NodaTime.Serialization.SystemTextJson 36 | - Added new ConfigureForNodaTimeWithSystemTextJson 37 | - Sample moved to net core 3 38 | - Sample supports NewtonsoftJson, System.Text.Json and System.Text.Json with NamingPolicy from NewtonsoftJson 39 | 40 | # 3.0.0-rc.1 41 | - Swashbuckle.AspNetCore updated to version 5.0.0-rc4 42 | 43 | # 2.0.0 44 | - Swashbuckle.AspNetCore fixed to versions [4.0.1, 5.0.0) 45 | 46 | # 1.2.0 47 | - Swashbuckle.AspNetCore fixed to versions [2.4.0, 4.0.1) 48 | 49 | # 1.1.0 50 | - Dependencies updated 51 | 52 | # 1.0.2 53 | - Bugfix: Uses factory instead of shared Schema instance. See: PR#3 54 | 55 | # 1.0.1 56 | - Updated package description 57 | 58 | # 1.0.0 59 | - Implemented in c#, no FSharp.Core lib in dependencies 60 | - JsonSerializerSettings ContractResolver uses for NamingStrategy, so you can use DefaultNamingStrategy, CamelCaseNamingStrategy or SnakeCaseNamingStrategy 61 | - Added new DateInterval (use NodaTime.Serialization.JsonNet >= 2.1.0) 62 | 63 | Full release notes can be found at: https://github.com/micro-elements/MicroElements.Swashbuckle.NodaTime/blob/master/CHANGELOG.md 64 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/NodaTimeSchemaSettings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using System; 5 | using NodaTime; 6 | 7 | namespace MicroElements.Swashbuckle.NodaTime 8 | { 9 | /// 10 | /// Settings that controls serialization aspects. 11 | /// 12 | public class NodaTimeSchemaSettings 13 | { 14 | /// 15 | /// Gets a function that resolves property name by proper naming strategy. 16 | /// 17 | public Func ResolvePropertyName { get; } 18 | 19 | /// 20 | /// Gets a function that formats object as json text. 21 | /// 22 | public Func FormatToJson { get; } 23 | 24 | /// 25 | /// Gets configured in Startup. 26 | /// 27 | public IDateTimeZoneProvider DateTimeZoneProvider { get; } 28 | 29 | /// 30 | /// Gets a value indicating whether example node should be generated. 31 | /// 32 | public bool ShouldGenerateExamples { get; } 33 | 34 | /// 35 | /// Gets for generation schema example values. 36 | /// 37 | public SchemaExamples SchemaExamples { get; } 38 | 39 | /// 40 | /// Initializes a new instance of the class. 41 | /// 42 | /// Function that resolves property name by proper naming strategy. 43 | /// Function that formats object as json text. 44 | /// Should the example node be generated. 45 | /// for schema example values. 46 | /// configured in Startup. 47 | public NodaTimeSchemaSettings( 48 | Func resolvePropertyName, 49 | Func formatToJson, 50 | bool shouldGenerateExamples, 51 | SchemaExamples? schemaExamples = null, 52 | IDateTimeZoneProvider? dateTimeZoneProvider = null) 53 | { 54 | ResolvePropertyName = resolvePropertyName; 55 | FormatToJson = formatToJson; 56 | 57 | DateTimeZoneProvider = dateTimeZoneProvider ?? DateTimeZoneProviders.Tzdb; 58 | 59 | ShouldGenerateExamples = shouldGenerateExamples; 60 | SchemaExamples = schemaExamples ?? new SchemaExamples( 61 | DateTimeZoneProvider, 62 | dateTimeUtc: null, 63 | dateTimeZone: null); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/Schemas.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using System; 5 | using Microsoft.OpenApi.Models; 6 | 7 | namespace MicroElements.Swashbuckle.NodaTime 8 | { 9 | /// 10 | /// Swagger schema generators. 11 | /// 12 | public class Schemas 13 | { 14 | /// 15 | /// Gets or sets schema generator for . 16 | /// 17 | public Func Instant { get; set; } = null!; 18 | 19 | /// 20 | /// Gets or sets schema generator for . 21 | /// 22 | public Func LocalDate { get; set; } = null!; 23 | 24 | /// 25 | /// Gets or sets schema generator for . 26 | /// 27 | public Func LocalTime { get; set; } = null!; 28 | 29 | /// 30 | /// Gets or sets schema generator for . 31 | /// 32 | public Func LocalDateTime { get; set; } = null!; 33 | 34 | /// 35 | /// Gets or sets schema generator for . 36 | /// 37 | public Func OffsetDateTime { get; set; } = null!; 38 | 39 | /// 40 | /// Gets or sets schema generator for . 41 | /// 42 | public Func ZonedDateTime { get; set; } = null!; 43 | 44 | /// 45 | /// Gets or sets schema generator for . 46 | /// 47 | public Func Interval { get; set; } = null!; 48 | 49 | /// 50 | /// Gets or sets schema generator for . 51 | /// 52 | public Func DateInterval { get; set; } = null!; 53 | 54 | /// 55 | /// Gets or sets schema generator for . 56 | /// 57 | public Func Offset { get; set; } = null!; 58 | 59 | /// 60 | /// Gets or sets schema generator for . 61 | /// 62 | public Func Period { get; set; } = null!; 63 | 64 | /// 65 | /// Gets or sets schema generator for . 66 | /// 67 | public Func Duration { get; set; } = null!; 68 | 69 | /// 70 | /// Gets or sets schema generator for . 71 | /// 72 | public Func OffsetDate { get; set; } = null!; 73 | 74 | /// 75 | /// Gets or sets schema generator for . 76 | /// 77 | public Func OffsetTime { get; set; } = null!; 78 | 79 | /// 80 | /// Gets or sets schema generator for . 81 | /// 82 | public Func DateTimeZone { get; set; } = null!; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/SchemasFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using System.Collections.Generic; 5 | using Microsoft.OpenApi.Any; 6 | using Microsoft.OpenApi.Models; 7 | using Newtonsoft.Json; 8 | using Newtonsoft.Json.Serialization; 9 | using NodaTime; 10 | 11 | namespace MicroElements.Swashbuckle.NodaTime 12 | { 13 | /// 14 | /// Factory for . 15 | /// 16 | public class SchemasFactory 17 | { 18 | private readonly NodaTimeSchemaSettings _settings; 19 | 20 | /// 21 | /// Initializes a new instance of the class. 22 | /// 23 | /// for serializing examples and for . 24 | public SchemasFactory(NodaTimeSchemaSettings settings) 25 | { 26 | _settings = settings; 27 | } 28 | 29 | /// 30 | /// Creates schemas container. 31 | /// 32 | /// Initialized instance. 33 | public Schemas CreateSchemas() 34 | { 35 | SchemaExamples examples = _settings.SchemaExamples; 36 | 37 | // https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14 38 | return new Schemas 39 | { 40 | Instant = () => StringSchema(examples.Instant, "date-time"), 41 | LocalDate = () => StringSchema(examples.ZonedDateTime.Date, "date"), 42 | LocalTime = () => StringSchema(examples.ZonedDateTime.TimeOfDay), 43 | LocalDateTime = () => StringSchema(examples.ZonedDateTime.LocalDateTime), 44 | OffsetDateTime = () => StringSchema(examples.OffsetDateTime, "date-time"), 45 | ZonedDateTime = () => StringSchema(examples.ZonedDateTime), 46 | Interval = () => new OpenApiSchema 47 | { 48 | Type = "object", 49 | Properties = new Dictionary 50 | { 51 | { ResolvePropertyName(nameof(Interval.Start)), StringSchema(examples.Interval.Start, "date-time") }, 52 | { ResolvePropertyName(nameof(Interval.End)), StringSchema(examples.Interval.End, "date-time") }, 53 | }, 54 | }, 55 | DateInterval = () => new OpenApiSchema 56 | { 57 | Type = "object", 58 | Properties = new Dictionary 59 | { 60 | { ResolvePropertyName(nameof(DateInterval.Start)), StringSchema(examples.DateInterval.Start, "date") }, 61 | { ResolvePropertyName(nameof(DateInterval.End)), StringSchema(examples.DateInterval.End, "date") }, 62 | }, 63 | }, 64 | Offset = () => StringSchema(examples.ZonedDateTime.Offset), 65 | Period = () => StringSchema(examples.Period), 66 | Duration = () => StringSchema(examples.Interval.Duration), 67 | OffsetDate = () => StringSchema(examples.OffsetDate), 68 | OffsetTime = () => StringSchema(examples.OffsetTime), 69 | DateTimeZone = () => StringSchema(examples.DateTimeZone), 70 | }; 71 | } 72 | 73 | private OpenApiSchema StringSchema(object exampleObject, string? format = null) 74 | { 75 | return new OpenApiSchema 76 | { 77 | Type = "string", 78 | Example = _settings.ShouldGenerateExamples 79 | ? new OpenApiString(FormatToJson(exampleObject)) 80 | : null, 81 | Format = format 82 | }; 83 | } 84 | 85 | private string ResolvePropertyName(string propertyName) 86 | { 87 | return _settings.ResolvePropertyName(propertyName); 88 | } 89 | 90 | private string FormatToJson(object value) 91 | { 92 | return _settings.FormatToJson(value); 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/SchemaExamples.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using System; 5 | using NodaTime; 6 | 7 | namespace MicroElements.Swashbuckle.NodaTime 8 | { 9 | /// 10 | /// Schema examples for schema generation. 11 | /// 12 | public class SchemaExamples 13 | { 14 | /// 15 | /// Gets or sets example. 16 | /// 17 | public DateTimeZone DateTimeZone { get; set; } 18 | 19 | /// 20 | /// Gets or sets example. 21 | /// 22 | public Instant Instant { get; set; } 23 | 24 | /// 25 | /// Gets or sets example. 26 | /// 27 | public ZonedDateTime ZonedDateTime { get; set; } 28 | 29 | /// 30 | /// Gets or sets example. 31 | /// 32 | public Interval Interval { get; set; } 33 | 34 | /// 35 | /// Gets or sets example. 36 | /// 37 | public DateInterval DateInterval { get; set; } 38 | 39 | /// 40 | /// Gets or sets example. 41 | /// 42 | public Period Period { get; set; } 43 | 44 | /// 45 | /// Gets or sets example. 46 | /// 47 | public OffsetDate OffsetDate { get; set; } 48 | 49 | /// 50 | /// Gets or sets example. 51 | /// 52 | public OffsetTime OffsetTime { get; set; } 53 | 54 | /// 55 | /// Gets or sets example. 56 | /// 57 | public OffsetDateTime OffsetDateTime { get; set; } 58 | 59 | /// 60 | /// Initializes a new instance of the class. 61 | /// Creates example value by provided and . 62 | /// 63 | /// IDateTimeZoneProvider instance. 64 | /// . If not set then will be used. 65 | /// Optional DateTimeZone name. If not set SystemDefault will be used. 66 | public SchemaExamples( 67 | IDateTimeZoneProvider dateTimeZoneProvider, 68 | DateTime? dateTimeUtc = null, 69 | string? dateTimeZone = null) 70 | { 71 | DateTime dateTimeUtcValue = dateTimeUtc ?? DateTime.UtcNow; 72 | if (dateTimeUtcValue.Kind != DateTimeKind.Utc) 73 | throw new ArgumentException("dateTimeUtc should be UTC", nameof(dateTimeUtc)); 74 | 75 | if (dateTimeZone != null) 76 | DateTimeZone = dateTimeZoneProvider.GetZoneOrNull(dateTimeZone) ?? dateTimeZoneProvider.GetSystemDefault(); 77 | else 78 | DateTimeZone = dateTimeZoneProvider.GetSystemDefault(); 79 | 80 | Instant = Instant.FromDateTimeUtc(dateTimeUtcValue); 81 | 82 | ZonedDateTime = Instant.InZone(DateTimeZone); 83 | 84 | Interval = new Interval(Instant, 85 | Instant.PlusTicks(TimeSpan.TicksPerDay) 86 | .PlusTicks(TimeSpan.TicksPerHour) 87 | .PlusTicks(TimeSpan.TicksPerMinute) 88 | .PlusTicks(TimeSpan.TicksPerSecond) 89 | .PlusTicks(TimeSpan.TicksPerMillisecond)); 90 | 91 | DateInterval = new DateInterval(ZonedDateTime.Date, ZonedDateTime.Date.PlusDays(1)); 92 | 93 | Period = Period.Between(ZonedDateTime.LocalDateTime, Interval.End.InZone(DateTimeZone).LocalDateTime, PeriodUnits.AllUnits); 94 | 95 | OffsetDate = new OffsetDate(ZonedDateTime.Date, ZonedDateTime.Offset); 96 | 97 | OffsetTime = new OffsetTime(ZonedDateTime.TimeOfDay, ZonedDateTime.Offset); 98 | 99 | OffsetDateTime = Instant.WithOffset(ZonedDateTime.Offset); 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/NodaTimeSchemaSettingsFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using System.Text.Json; 5 | using Newtonsoft.Json; 6 | using Newtonsoft.Json.Serialization; 7 | using NodaTime; 8 | 9 | namespace MicroElements.Swashbuckle.NodaTime 10 | { 11 | /// 12 | /// Factory methods for . 13 | /// 14 | public static class NodaTimeSchemaSettingsFactory 15 | { 16 | /// 17 | /// Creates for NewtonsoftJson. 18 | /// 19 | /// . 20 | /// Should generate example for schema. 21 | /// for schema example values. 22 | /// Optional . 23 | /// . 24 | public static NodaTimeSchemaSettings CreateNodaTimeSchemaSettingsForNewtonsoftJson( 25 | this JsonSerializerSettings serializerSettings, 26 | bool shouldGenerateExamples = true, 27 | SchemaExamples? schemaExamples = null, 28 | IDateTimeZoneProvider? dateTimeZoneProvider = null) 29 | { 30 | string FormatToJson(object value) 31 | { 32 | string formatToJson = JsonConvert.SerializeObject(value, serializerSettings); 33 | if (formatToJson.StartsWith("\"") && formatToJson.EndsWith("\"")) 34 | formatToJson = formatToJson.Substring(1, formatToJson.Length - 2); 35 | return formatToJson; 36 | } 37 | 38 | string ResolvePropertyName(string propertyName) 39 | { 40 | return (serializerSettings.ContractResolver as DefaultContractResolver)?.GetResolvedPropertyName(propertyName) ?? propertyName; 41 | } 42 | 43 | return new NodaTimeSchemaSettings( 44 | ResolvePropertyName, 45 | FormatToJson, 46 | shouldGenerateExamples, 47 | schemaExamples, 48 | dateTimeZoneProvider); 49 | } 50 | 51 | /// 52 | /// Creates for SystemTextJson. 53 | /// 54 | /// . 55 | /// Should generate example for schema. 56 | /// for schema example values. 57 | /// Optional . 58 | /// . 59 | public static NodaTimeSchemaSettings CreateNodaTimeSchemaSettingsForSystemTextJson( 60 | this JsonSerializerOptions jsonSerializerOptions, 61 | bool shouldGenerateExamples = true, 62 | SchemaExamples? schemaExamples = null, 63 | IDateTimeZoneProvider? dateTimeZoneProvider = null) 64 | { 65 | string FormatToJson(object value) 66 | { 67 | if (value is DateTimeZone dateTimeZone) 68 | { 69 | // TODO: remove after PR released: https://github.com/nodatime/nodatime.serialization/pull/57 70 | return dateTimeZone.Id; 71 | } 72 | 73 | string formatToJson = System.Text.Json.JsonSerializer.Serialize(value, jsonSerializerOptions); 74 | if (formatToJson.StartsWith("\"") && formatToJson.EndsWith("\"")) 75 | formatToJson = formatToJson.Substring(1, formatToJson.Length - 2); 76 | return formatToJson; 77 | } 78 | 79 | string ResolvePropertyName(string propertyName) 80 | { 81 | return jsonSerializerOptions.PropertyNamingPolicy?.ConvertName(propertyName) ?? propertyName; 82 | } 83 | 84 | return new NodaTimeSchemaSettings( 85 | ResolvePropertyName, 86 | FormatToJson, 87 | shouldGenerateExamples, 88 | schemaExamples, 89 | dateTimeZoneProvider); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /MicroElements.Swashbuckle.NodaTime.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29613.14 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{6B66F586-EF92-418F-AC6E-4BF4C52411D3}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroElements.Swashbuckle.NodaTime", "src\MicroElements.Swashbuckle.NodaTime\MicroElements.Swashbuckle.NodaTime.csproj", "{AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{09A81706-5AAC-4D3B-81FB-BD4DD28D03CB}" 11 | ProjectSection(SolutionItems) = preProject 12 | test\Directory.Build.props = test\Directory.Build.props 13 | EndProjectSection 14 | EndProject 15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicroElements.Swashbuckle.NodaTime.Tests", "test\MicroElements.Swashbuckle.NodaTime.Tests\MicroElements.Swashbuckle.NodaTime.Tests.csproj", "{798200FF-E54C-428F-A814-6CF9779DCE39}" 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{3FEFEC89-F7E7-46E7-BBA6-7EF5D609B7A2}" 18 | EndProject 19 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApiSample", "samples\WebApiSample\WebApiSample.csproj", "{6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}" 20 | EndProject 21 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{18EDFD87-A526-4C48-9E3E-649D230F3580}" 22 | ProjectSection(SolutionItems) = preProject 23 | .travis.yml = .travis.yml 24 | CHANGELOG.md = CHANGELOG.md 25 | common.props = common.props 26 | src\Directory.Build.props = src\Directory.Build.props 27 | README.md = README.md 28 | src\stylecop.json = src\stylecop.json 29 | src\stylecop.props = src\stylecop.props 30 | src\stylecop.ruleset = src\stylecop.ruleset 31 | version.props = version.props 32 | EndProjectSection 33 | EndProject 34 | Global 35 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 36 | Debug|Any CPU = Debug|Any CPU 37 | Debug|x64 = Debug|x64 38 | Debug|x86 = Debug|x86 39 | Release|Any CPU = Release|Any CPU 40 | Release|x64 = Release|x64 41 | Release|x86 = Release|x86 42 | EndGlobalSection 43 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 44 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Debug|x64.ActiveCfg = Debug|Any CPU 47 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Debug|x64.Build.0 = Debug|Any CPU 48 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Debug|x86.ActiveCfg = Debug|Any CPU 49 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Debug|x86.Build.0 = Debug|Any CPU 50 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Release|x64.ActiveCfg = Release|Any CPU 53 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Release|x64.Build.0 = Release|Any CPU 54 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Release|x86.ActiveCfg = Release|Any CPU 55 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F}.Release|x86.Build.0 = Release|Any CPU 56 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Debug|x64.ActiveCfg = Debug|Any CPU 59 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Debug|x64.Build.0 = Debug|Any CPU 60 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Debug|x86.ActiveCfg = Debug|Any CPU 61 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Debug|x86.Build.0 = Debug|Any CPU 62 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Release|Any CPU.ActiveCfg = Release|Any CPU 63 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Release|Any CPU.Build.0 = Release|Any CPU 64 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Release|x64.ActiveCfg = Release|Any CPU 65 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Release|x64.Build.0 = Release|Any CPU 66 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Release|x86.ActiveCfg = Release|Any CPU 67 | {798200FF-E54C-428F-A814-6CF9779DCE39}.Release|x86.Build.0 = Release|Any CPU 68 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 69 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Debug|Any CPU.Build.0 = Debug|Any CPU 70 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Debug|x64.ActiveCfg = Debug|Any CPU 71 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Debug|x64.Build.0 = Debug|Any CPU 72 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Debug|x86.ActiveCfg = Debug|Any CPU 73 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Debug|x86.Build.0 = Debug|Any CPU 74 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Release|Any CPU.ActiveCfg = Release|Any CPU 75 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Release|Any CPU.Build.0 = Release|Any CPU 76 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Release|x64.ActiveCfg = Release|Any CPU 77 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Release|x64.Build.0 = Release|Any CPU 78 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Release|x86.ActiveCfg = Release|Any CPU 79 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425}.Release|x86.Build.0 = Release|Any CPU 80 | EndGlobalSection 81 | GlobalSection(SolutionProperties) = preSolution 82 | HideSolutionNode = FALSE 83 | EndGlobalSection 84 | GlobalSection(NestedProjects) = preSolution 85 | {AAC5EC68-5313-48AC-B25B-3B3B4611AE4F} = {6B66F586-EF92-418F-AC6E-4BF4C52411D3} 86 | {798200FF-E54C-428F-A814-6CF9779DCE39} = {09A81706-5AAC-4D3B-81FB-BD4DD28D03CB} 87 | {6E7D915A-9EE2-4ADA-B8C9-D0B934F4B425} = {3FEFEC89-F7E7-46E7-BBA6-7EF5D609B7A2} 88 | EndGlobalSection 89 | GlobalSection(ExtensibilityGlobals) = postSolution 90 | SolutionGuid = {0C0A56C4-3421-4F73-9F82-BD34B0C7D233} 91 | EndGlobalSection 92 | EndGlobal 93 | -------------------------------------------------------------------------------- /test/MicroElements.Swashbuckle.NodaTime.Tests/SchemasTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.Encodings.Web; 3 | using System.Text.Json; 4 | using FluentAssertions; 5 | using Microsoft.OpenApi.Any; 6 | using Newtonsoft.Json; 7 | using NodaTime; 8 | using NodaTime.Serialization.JsonNet; 9 | using NodaTime.Serialization.SystemTextJson; 10 | using Xunit; 11 | 12 | namespace MicroElements.Swashbuckle.NodaTime.Tests 13 | { 14 | public class SchemasTests 15 | { 16 | [Fact] 17 | public void NewtonsoftJsonSettingsTest() 18 | { 19 | IDateTimeZoneProvider dateTimeZoneProvider = DateTimeZoneProviders.Tzdb; 20 | DateTime dateTimeUtc = new DateTime(2020, 05, 23, 10, 30, 50, DateTimeKind.Utc); 21 | 22 | var schemaExamples = new SchemaExamples(dateTimeZoneProvider, dateTimeUtc, "Europe/Moscow"); 23 | var nodaTimeSchemaSettings = new JsonSerializerSettings() 24 | .ConfigureForNodaTime(dateTimeZoneProvider) 25 | .CreateNodaTimeSchemaSettingsForNewtonsoftJson(schemaExamples: schemaExamples); 26 | 27 | CheckGeneratedSchema(nodaTimeSchemaSettings); 28 | } 29 | 30 | [Fact] 31 | public void SystemTextJsonSettingsTest() 32 | { 33 | IDateTimeZoneProvider dateTimeZoneProvider = DateTimeZoneProviders.Tzdb; 34 | DateTime dateTimeUtc = new DateTime(2020, 05, 23, 10, 30, 50, DateTimeKind.Utc); 35 | 36 | var schemaExamples = new SchemaExamples(dateTimeZoneProvider, dateTimeUtc, "Europe/Moscow"); 37 | var jsonSerializerOptions = new JsonSerializerOptions {Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping}; 38 | var nodaTimeSchemaSettings = jsonSerializerOptions 39 | .ConfigureForNodaTime(dateTimeZoneProvider) 40 | .CreateNodaTimeSchemaSettingsForSystemTextJson(schemaExamples: schemaExamples); 41 | 42 | CheckGeneratedSchema(nodaTimeSchemaSettings); 43 | } 44 | 45 | private static void CheckGeneratedSchema(NodaTimeSchemaSettings nodaTimeSchemaSettings) 46 | { 47 | Schemas schemas = new SchemasFactory(nodaTimeSchemaSettings).CreateSchemas(); 48 | 49 | schemas.Instant().Type.Should().Be("string"); 50 | schemas.Instant().Format.Should().Be("date-time"); 51 | schemas.Instant().Example.AsString().Should().Be("2020-05-23T10:30:50Z"); 52 | 53 | schemas.LocalDate().Type.Should().Be("string"); 54 | schemas.LocalDate().Format.Should().Be("date"); 55 | schemas.LocalDate().Example.AsString().Should().Be("2020-05-23"); 56 | 57 | schemas.LocalTime().Type.Should().Be("string"); 58 | schemas.LocalTime().Format.Should().Be(null); 59 | schemas.LocalTime().Example.AsString().Should().Be("13:30:50"); 60 | 61 | schemas.LocalDateTime().Type.Should().Be("string"); 62 | schemas.LocalDateTime().Format.Should().Be(null); 63 | schemas.LocalDateTime().Example.AsString().Should().Be("2020-05-23T13:30:50"); 64 | 65 | schemas.OffsetDateTime().Type.Should().Be("string"); 66 | schemas.OffsetDateTime().Format.Should().Be("date-time"); 67 | schemas.OffsetDateTime().Example.AsString().Should().Be("2020-05-23T13:30:50+03:00"); 68 | 69 | schemas.ZonedDateTime().Type.Should().Be("string"); 70 | schemas.ZonedDateTime().Format.Should().Be(null); 71 | schemas.ZonedDateTime().Example.AsString().Should().Be("2020-05-23T13:30:50+03 Europe/Moscow"); 72 | 73 | schemas.Interval().Type.Should().Be("object"); 74 | schemas.Interval().Properties["Start"].Example.AsString().Should().Be("2020-05-23T10:30:50Z"); 75 | schemas.Interval().Properties["End"].Example.AsString().Should().Be("2020-05-24T11:31:51.001Z"); 76 | 77 | schemas.DateInterval().Type.Should().Be("object"); 78 | schemas.DateInterval().Properties["Start"].Example.AsString().Should().Be("2020-05-23"); 79 | schemas.DateInterval().Properties["End"].Example.AsString().Should().Be("2020-05-24"); 80 | 81 | schemas.Offset().Type.Should().Be("string"); 82 | schemas.Offset().Format.Should().Be(null); 83 | schemas.Offset().Example.AsString().Should().Be("+03"); 84 | 85 | schemas.Period().Type.Should().Be("string"); 86 | schemas.Period().Format.Should().Be(null); 87 | schemas.Period().Example.AsString().Should().Be("P1DT1H1M1S1s"); 88 | 89 | schemas.Duration().Type.Should().Be("string"); 90 | schemas.Duration().Format.Should().Be(null); 91 | schemas.Duration().Example.AsString().Should().Be("25:01:01.001"); 92 | 93 | schemas.OffsetDate().Type.Should().Be("string"); 94 | schemas.OffsetDate().Format.Should().Be(null); 95 | schemas.OffsetDate().Example.AsString().Should().Be("2020-05-23+03"); 96 | 97 | schemas.OffsetTime().Type.Should().Be("string"); 98 | schemas.OffsetTime().Format.Should().Be(null); 99 | schemas.OffsetTime().Example.AsString().Should().Be("13:30:50+03"); 100 | 101 | schemas.DateTimeZone().Type.Should().Be("string"); 102 | schemas.DateTimeZone().Format.Should().Be(null); 103 | schemas.DateTimeZone().Example.AsString().Should().Be("Europe/Moscow"); 104 | } 105 | } 106 | 107 | internal static class TestExtensions 108 | { 109 | public static string AsString(this IOpenApiAny openApiAny) 110 | { 111 | if (openApiAny is OpenApiString openApiString) 112 | return openApiString.Value; 113 | 114 | return openApiAny.ToString(); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Default settings: 7 | # A newline ending every file 8 | # Use 4 spaces as indentation 9 | [*] 10 | insert_final_newline = true 11 | indent_style = space 12 | indent_size = 4 13 | 14 | [project.json] 15 | indent_size = 2 16 | 17 | # C# files 18 | [*.cs] 19 | # New line preferences 20 | csharp_new_line_before_open_brace = all 21 | csharp_new_line_before_else = true 22 | csharp_new_line_before_catch = true 23 | csharp_new_line_before_finally = true 24 | csharp_new_line_before_members_in_object_initializers = true 25 | csharp_new_line_before_members_in_anonymous_types = true 26 | csharp_new_line_within_query_expression_clauses = true 27 | 28 | # Indentation preferences 29 | csharp_indent_block_contents = true 30 | csharp_indent_braces = false 31 | csharp_indent_case_contents = true 32 | csharp_indent_switch_labels = true 33 | csharp_indent_labels = flush_left 34 | 35 | # avoid this. unless absolutely necessary 36 | dotnet_style_qualification_for_field = false:suggestion 37 | dotnet_style_qualification_for_property = false:suggestion 38 | dotnet_style_qualification_for_method = false:suggestion 39 | dotnet_style_qualification_for_event = false:suggestion 40 | 41 | # only use var when it's obvious what the variable type is 42 | csharp_style_var_for_built_in_types = false:none 43 | csharp_style_var_when_type_is_apparent = false:none 44 | csharp_style_var_elsewhere = false:suggestion 45 | 46 | # use language keywords instead of BCL types 47 | dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion 48 | dotnet_style_predefined_type_for_member_access = true:suggestion 49 | 50 | # name all constant fields using PascalCase 51 | dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion 52 | dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields 53 | dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style 54 | 55 | dotnet_naming_symbols.constant_fields.applicable_kinds = field 56 | dotnet_naming_symbols.constant_fields.required_modifiers = const 57 | 58 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case 59 | 60 | # static fields should have s_ prefix 61 | dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion 62 | dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields 63 | dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style 64 | 65 | dotnet_naming_symbols.static_fields.applicable_kinds = field 66 | dotnet_naming_symbols.static_fields.required_modifiers = static 67 | 68 | dotnet_naming_style.static_prefix_style.required_prefix = s_ 69 | dotnet_naming_style.static_prefix_style.capitalization = camel_case 70 | 71 | # internal and private fields should be _camelCase 72 | dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion 73 | dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields 74 | dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style 75 | 76 | dotnet_naming_symbols.private_internal_fields.applicable_kinds = field 77 | dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal 78 | 79 | dotnet_naming_style.camel_case_underscore_style.required_prefix = _ 80 | dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case 81 | 82 | # Code style defaults 83 | dotnet_sort_system_directives_first = true 84 | csharp_preserve_single_line_blocks = true 85 | csharp_preserve_single_line_statements = false 86 | 87 | # Expression-level preferences 88 | dotnet_style_object_initializer = true:suggestion 89 | dotnet_style_collection_initializer = true:suggestion 90 | dotnet_style_explicit_tuple_names = true:suggestion 91 | dotnet_style_coalesce_expression = true:suggestion 92 | dotnet_style_null_propagation = true:suggestion 93 | 94 | # Expression-bodied members 95 | csharp_style_expression_bodied_methods = false:none 96 | csharp_style_expression_bodied_constructors = false:none 97 | csharp_style_expression_bodied_operators = false:none 98 | csharp_style_expression_bodied_properties = true:none 99 | csharp_style_expression_bodied_indexers = true:none 100 | csharp_style_expression_bodied_accessors = true:none 101 | 102 | # Pattern matching 103 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 104 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 105 | csharp_style_inlined_variable_declaration = true:suggestion 106 | 107 | # Null checking preferences 108 | csharp_style_throw_expression = true:suggestion 109 | csharp_style_conditional_delegate_call = true:suggestion 110 | 111 | # Space preferences 112 | csharp_space_after_cast = false 113 | csharp_space_after_colon_in_inheritance_clause = true 114 | csharp_space_after_comma = true 115 | csharp_space_after_dot = false 116 | csharp_space_after_keywords_in_control_flow_statements = true 117 | csharp_space_after_semicolon_in_for_statement = true 118 | csharp_space_around_binary_operators = before_and_after 119 | csharp_space_around_declaration_statements = do_not_ignore 120 | csharp_space_before_colon_in_inheritance_clause = true 121 | csharp_space_before_comma = false 122 | csharp_space_before_dot = false 123 | csharp_space_before_open_square_brackets = false 124 | csharp_space_before_semicolon_in_for_statement = false 125 | csharp_space_between_empty_square_brackets = false 126 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 127 | csharp_space_between_method_call_name_and_opening_parenthesis = false 128 | csharp_space_between_method_call_parameter_list_parentheses = false 129 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 130 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 131 | csharp_space_between_method_declaration_parameter_list_parentheses = false 132 | csharp_space_between_parentheses = false 133 | csharp_space_between_square_brackets = false 134 | 135 | # C++ Files 136 | 137 | # IDE0055: Fix formatting 138 | dotnet_diagnostic.IDE0055.severity = none 139 | 140 | [*.{cpp,h,in}] 141 | curly_bracket_next_line = true 142 | indent_brace_style = Allman 143 | 144 | # Xml project files 145 | [*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] 146 | indent_size = 2 147 | 148 | # Xml build files 149 | [*.builds] 150 | indent_size = 2 151 | 152 | # Xml files 153 | [*.{xml,stylecop,resx,ruleset}] 154 | indent_size = 2 155 | 156 | # Xml config files 157 | [*.{props,targets,config,nuspec}] 158 | indent_size = 2 159 | 160 | # Shell scripts 161 | [*.sh] 162 | end_of_line = lf 163 | [*.{cmd, bat}] 164 | end_of_line = crlf 165 | -------------------------------------------------------------------------------- /samples/WebApiSample/Startup.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Encodings.Web; 2 | using System.Text.Json; 3 | using MicroElements.Swashbuckle.NodaTime; 4 | using Microsoft.AspNetCore.Builder; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Options; 8 | using Microsoft.OpenApi.Models; 9 | using Newtonsoft.Json; 10 | using Newtonsoft.Json.Serialization; 11 | using NodaTime; 12 | using NodaTime.Serialization.JsonNet; 13 | using NodaTime.Serialization.SystemTextJson; 14 | 15 | namespace WebApiSample 16 | { 17 | public class Startup 18 | { 19 | enum JsonProvider 20 | { 21 | NewtonsoftJson, 22 | SystemTextJson 23 | } 24 | 25 | // JsonProvider 26 | private static JsonProvider useJsonProvider = JsonProvider.SystemTextJson; 27 | 28 | // USING NewtonsoftJson settings as PropertyNamingPolicy for System.Text.Json 29 | private static bool useNewtonsoftJsonAsNamingPolicy = true; 30 | 31 | // This method gets called by the runtime. Use this method to add services to the container. 32 | public void ConfigureServices(IServiceCollection services) 33 | { 34 | void ConfigureNewtonsoftJsonSerializerSettings(JsonSerializerSettings serializerSettings) 35 | { 36 | // Use DefaultContractResolver or CamelCasePropertyNamesContractResolver; 37 | // serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 38 | serializerSettings.ContractResolver = new DefaultContractResolver() 39 | { 40 | //NamingStrategy = new DefaultNamingStrategy() 41 | //NamingStrategy = new CamelCaseNamingStrategy() 42 | //NamingStrategy = new SnakeCaseNamingStrategy() 43 | NamingStrategy = new CamelCaseNamingStrategy() 44 | }; 45 | 46 | // Configures JsonSerializer to properly serialize NodaTime types. 47 | serializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); 48 | } 49 | 50 | void ConfigureSystemTextJsonSerializerSettings(JsonSerializerOptions serializerOptions) 51 | { 52 | if (useNewtonsoftJsonAsNamingPolicy) 53 | { 54 | // USING NewtonsoftJson settings as PropertyNamingPolicy for System.Text.Json 55 | JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings(); 56 | ConfigureNewtonsoftJsonSerializerSettings(jsonSerializerSettings); 57 | serializerOptions.PropertyNamingPolicy = new NewtonsoftJsonNamingPolicy(jsonSerializerSettings); 58 | } 59 | 60 | // Configures JsonSerializer to properly serialize NodaTime types. 61 | serializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); 62 | 63 | serializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; 64 | } 65 | 66 | if (useJsonProvider == JsonProvider.NewtonsoftJson) 67 | { 68 | services 69 | .AddMvcCore() 70 | .AddApiExplorer() 71 | .AddNewtonsoftJson(options => ConfigureNewtonsoftJsonSerializerSettings(options.SerializerSettings)); 72 | } 73 | 74 | if (useJsonProvider == JsonProvider.SystemTextJson) 75 | { 76 | services 77 | .AddMvcCore() 78 | .AddApiExplorer() 79 | .AddJsonOptions(options => ConfigureSystemTextJsonSerializerSettings(options.JsonSerializerOptions)) 80 | ; 81 | } 82 | 83 | //services.AddTransient, ConfigureNewtonsoftJsonJsonNamingPolicy>(); 84 | 85 | // Adds swagger 86 | services.AddSwaggerGen(c => 87 | { 88 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 89 | 90 | if (useJsonProvider == JsonProvider.NewtonsoftJson) 91 | { 92 | // Configures swagger to use NodaTime with serializerSettings. 93 | c.ConfigureForNodaTime(configureSerializerSettings: ConfigureNewtonsoftJsonSerializerSettings, shouldGenerateExamples: true); 94 | } 95 | 96 | if (useJsonProvider == JsonProvider.SystemTextJson) 97 | { 98 | JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(); 99 | ConfigureSystemTextJsonSerializerSettings(jsonSerializerOptions); 100 | c.ConfigureForNodaTimeWithSystemTextJson(jsonSerializerOptions, shouldGenerateExamples: true); 101 | } 102 | }); 103 | } 104 | 105 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 106 | public void Configure(IApplicationBuilder app) 107 | { 108 | app.UseSwagger(); 109 | app.UseRouting(); 110 | app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); 111 | 112 | // Adds swagger UI 113 | app.UseSwaggerUI(c => 114 | { 115 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); 116 | }); 117 | } 118 | } 119 | 120 | public class NewtonsoftJsonNamingPolicy : JsonNamingPolicy 121 | { 122 | private readonly JsonSerializerSettings _jsonSerializerSettings; 123 | 124 | /// 125 | public NewtonsoftJsonNamingPolicy(JsonSerializerSettings jsonSerializerSettings) 126 | { 127 | _jsonSerializerSettings = jsonSerializerSettings; 128 | } 129 | 130 | /// 131 | public override string ConvertName(string name) 132 | { 133 | var contractResolver = _jsonSerializerSettings.ContractResolver; 134 | return (contractResolver as DefaultContractResolver)?.GetResolvedPropertyName(name) ?? name; 135 | } 136 | } 137 | 138 | public class ConfigureNewtonsoftJsonJsonNamingPolicy : IConfigureOptions 139 | { 140 | private readonly IOptions _newtonsoftJsonOptions; 141 | 142 | public ConfigureNewtonsoftJsonJsonNamingPolicy(IOptions newtonsoftJsonOptions) 143 | { 144 | _newtonsoftJsonOptions = newtonsoftJsonOptions; 145 | } 146 | 147 | /// 148 | public void Configure(JsonOptions options) 149 | { 150 | options.JsonSerializerOptions.PropertyNamingPolicy = new NewtonsoftJsonNamingPolicy(_newtonsoftJsonOptions.Value.SerializerSettings); 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/MicroElements.Swashbuckle.NodaTime/SwaggerGenOptionsExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) MicroElements. All rights reserved. 2 | // Licensed under the MIT license. See LICENSE file in the project root for full license information. 3 | 4 | using System; 5 | using System.Linq; 6 | using System.Text.Json; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Newtonsoft.Json; 9 | using NodaTime; 10 | using NodaTime.Serialization.JsonNet; 11 | using Swashbuckle.AspNetCore.SwaggerGen; 12 | 13 | namespace MicroElements.Swashbuckle.NodaTime 14 | { 15 | /// 16 | /// Extensions for configuring swagger to use NodaTime types. 17 | /// 18 | public static class SwaggerGenOptionsExtensions 19 | { 20 | /// 21 | /// Configures swagger to use NodaTime types. 22 | /// Uses NewtonsoftJson for serialization aspects. 23 | /// 24 | /// SwaggerGenOptions. 25 | /// Optional serializer settings. 26 | /// Optional action to configure serializerSettings. 27 | /// Optional DateTimeZoneProviders. 28 | /// Should generate example for schema. 29 | /// for schema example values. 30 | public static void ConfigureForNodaTime( 31 | this SwaggerGenOptions config, 32 | JsonSerializerSettings? serializerSettings = null, 33 | Action? configureSerializerSettings = null, 34 | IDateTimeZoneProvider? dateTimeZoneProvider = null, 35 | bool shouldGenerateExamples = true, 36 | SchemaExamples? schemaExamples = null) 37 | { 38 | if (config == null) 39 | throw new ArgumentNullException(nameof(config)); 40 | 41 | serializerSettings ??= new JsonSerializerSettings(); 42 | configureSerializerSettings?.Invoke(serializerSettings); 43 | 44 | bool isNodaConvertersRegistered = serializerSettings.Converters.Any(converter => converter is NodaConverterBase); 45 | if (!isNodaConvertersRegistered) 46 | { 47 | serializerSettings.ConfigureForNodaTime(dateTimeZoneProvider ?? DateTimeZoneProviders.Tzdb); 48 | } 49 | 50 | var nodaTimeSchemaSettings = serializerSettings.CreateNodaTimeSchemaSettingsForNewtonsoftJson( 51 | dateTimeZoneProvider: dateTimeZoneProvider, 52 | shouldGenerateExamples: shouldGenerateExamples, 53 | schemaExamples: schemaExamples); 54 | config.ConfigureForNodaTime(nodaTimeSchemaSettings); 55 | } 56 | 57 | /// 58 | /// Configures swagger to use NodaTime types. 59 | /// Uses System.Text.Json for serialization aspects. 60 | /// 61 | /// SwaggerGenOptions. 62 | /// Optional serializer options. 63 | /// Optional action to configure jsonSerializerOptions. 64 | /// Optional DateTimeZoneProviders. 65 | /// Should generate example for schema. 66 | /// for schema example values. 67 | public static void ConfigureForNodaTimeWithSystemTextJson( 68 | this SwaggerGenOptions config, 69 | JsonSerializerOptions? jsonSerializerOptions = null, 70 | Action? configureSerializerOptions = null, 71 | IDateTimeZoneProvider? dateTimeZoneProvider = null, 72 | bool shouldGenerateExamples = true, 73 | SchemaExamples? schemaExamples = null) 74 | { 75 | if (config == null) 76 | throw new ArgumentNullException(nameof(config)); 77 | 78 | jsonSerializerOptions ??= new JsonSerializerOptions(); 79 | configureSerializerOptions?.Invoke(jsonSerializerOptions); 80 | 81 | global::NodaTime.Serialization.SystemTextJson.Extensions.ConfigureForNodaTime(jsonSerializerOptions, 82 | dateTimeZoneProvider ?? DateTimeZoneProviders.Tzdb); 83 | 84 | var nodaTimeSchemaSettings = jsonSerializerOptions.CreateNodaTimeSchemaSettingsForSystemTextJson( 85 | dateTimeZoneProvider: dateTimeZoneProvider, 86 | shouldGenerateExamples: shouldGenerateExamples, 87 | schemaExamples: schemaExamples); 88 | config.ConfigureForNodaTime(nodaTimeSchemaSettings); 89 | } 90 | 91 | /// 92 | /// Configures swagger to use NodaTime types. 93 | /// 94 | /// Options to configure swagger. 95 | /// Settings to configure serialization. 96 | public static void ConfigureForNodaTime(this SwaggerGenOptions config, NodaTimeSchemaSettings nodaTimeSchemaSettings) 97 | { 98 | config.ParameterFilter(nodaTimeSchemaSettings); 99 | 100 | Schemas schemas = new SchemasFactory(nodaTimeSchemaSettings).CreateSchemas(); 101 | 102 | config.MapType (schemas.Instant); 103 | config.MapType (schemas.LocalDate); 104 | config.MapType (schemas.LocalTime); 105 | config.MapType (schemas.LocalDateTime); 106 | config.MapType (schemas.OffsetDateTime); 107 | config.MapType (schemas.ZonedDateTime); 108 | config.MapType (schemas.Interval); 109 | config.MapType (schemas.DateInterval); 110 | config.MapType (schemas.Offset); 111 | config.MapType (schemas.Period); 112 | config.MapType (schemas.Duration); 113 | config.MapType (schemas.OffsetDate); 114 | config.MapType (schemas.OffsetTime); 115 | config.MapType (schemas.DateTimeZone); 116 | 117 | // Nullable structs 118 | config.MapType (schemas.Instant); 119 | config.MapType (schemas.LocalDate); 120 | config.MapType (schemas.LocalTime); 121 | config.MapType (schemas.LocalDateTime); 122 | config.MapType(schemas.OffsetDateTime); 123 | config.MapType (schemas.ZonedDateTime); 124 | config.MapType (schemas.Interval); 125 | config.MapType (schemas.Offset); 126 | config.MapType (schemas.Duration); 127 | config.MapType (schemas.OffsetDate); 128 | config.MapType (schemas.OffsetTime); 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MicroElements.Swashbuckle.NodaTime 2 | Allows configure Asp.Net Core and swagger to use NodaTime types. 3 | 4 | ## Latest Builds, Packages 5 | [![License](http://img.shields.io/:license-mit-blue.svg)](https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/master/LICENSE) 6 | [![NuGet](https://img.shields.io/nuget/v/MicroElements.Swashbuckle.NodaTime.svg)](https://www.nuget.org/packages/MicroElements.Swashbuckle.NodaTime) 7 | ![NuGet](https://img.shields.io/nuget/dt/MicroElements.Swashbuckle.NodaTime.svg) 8 | [![MyGet](https://img.shields.io/myget/micro-elements/v/MicroElements.Swashbuckle.NodaTime.svg)](https://www.myget.org/feed/micro-elements/package/nuget/MicroElements.Swashbuckle.NodaTime) 9 | 10 | [![Travis](https://img.shields.io/travis/micro-elements/MicroElements.Swashbuckle.NodaTime/master.svg?logo=travis)](https://travis-ci.org/micro-elements/MicroElements.Swashbuckle.NodaTime) 11 | [![AppVeyor](https://img.shields.io/appveyor/ci/micro-elements/microelements-swashbuckle-nodatime.svg?logo=appveyor)](https://ci.appveyor.com/project/micro-elements/microelements-swashbuckle-nodatime) 12 | [![Coverage Status](https://img.shields.io/coveralls/micro-elements/MicroElements.Swashbuckle.NodaTime.svg)](https://coveralls.io/r/micro-elements/MicroElements.Swashbuckle.NodaTime) 13 | 14 | [![Gitter](https://img.shields.io/gitter/room/micro-elements/MicroElements.Swashbuckle.NodaTime.svg)](https://gitter.im/micro-elements/MicroElements.Swashbuckle.NodaTime) 15 | 16 | ## Installation 17 | 18 | ### Package Reference: 19 | 20 | ``` 21 | dotnet add package microelements.swashbuckle.nodatime 22 | ``` 23 | 24 | ## Getting started 25 | - Add package reference to MicroElements.Swashbuckle.NodaTime 26 | - Configure asp net core to use swagger 27 | - Configure JsonSerializer to properly serialize NodaTime types. see `AddJsonFormatters` or `AddJsonOptions` 28 | - Configure `AddSwaggerGen` with `ConfigureForNodaTime` 29 | 30 | ## Benefits of MicroElements.Swashbuckle.NodaTime 31 | - Supports Swashbuckle 5, net core 3 and brand new System.Text.Json 32 | - Implemented in c#, no FSharp.Core lib in dependencies 33 | - JsonSerializerSettings ContractResolver uses for NamingStrategy, so you can use DefaultNamingStrategy, CamelCaseNamingStrategy or SnakeCaseNamingStrategy 34 | - Supports new DateInterval (use NodaTime.Serialization.JsonNet >= 2.1.0) 35 | 36 | ## Sample 37 | 38 | Full sample see in samples: https://github.com/micro-elements/MicroElements.Swashbuckle.NodaTime/tree/master/samples/WebApiSample 39 | 40 | ```csharp 41 | public class Startup 42 | { 43 | enum JsonProvider 44 | { 45 | NewtonsoftJson, 46 | SystemTextJson 47 | } 48 | 49 | // JsonProvider 50 | private static JsonProvider useJsonProvider = JsonProvider.SystemTextJson; 51 | 52 | // USING NewtonsoftJson settings as PropertyNamingPolicy for System.Text.Json 53 | private static bool useNewtonsoftJsonAsNamingPolicy = true; 54 | 55 | // This method gets called by the runtime. Use this method to add services to the container. 56 | public void ConfigureServices(IServiceCollection services) 57 | { 58 | void ConfigureNewtonsoftJsonSerializerSettings(JsonSerializerSettings serializerSettings) 59 | { 60 | // Use DefaultContractResolver or CamelCasePropertyNamesContractResolver; 61 | // serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 62 | serializerSettings.ContractResolver = new DefaultContractResolver() 63 | { 64 | //NamingStrategy = new DefaultNamingStrategy() 65 | //NamingStrategy = new CamelCaseNamingStrategy() 66 | //NamingStrategy = new SnakeCaseNamingStrategy() 67 | NamingStrategy = new CamelCaseNamingStrategy() 68 | }; 69 | 70 | // Configures JsonSerializer to properly serialize NodaTime types. 71 | serializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); 72 | } 73 | 74 | void ConfigureSystemTextJsonSerializerSettings(JsonSerializerOptions serializerOptions) 75 | { 76 | if (useNewtonsoftJsonAsNamingPolicy) 77 | { 78 | // USING NewtonsoftJson settings as PropertyNamingPolicy for System.Text.Json 79 | JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings(); 80 | ConfigureNewtonsoftJsonSerializerSettings(jsonSerializerSettings); 81 | serializerOptions.PropertyNamingPolicy = new NewtonsoftJsonNamingPolicy(jsonSerializerSettings); 82 | } 83 | 84 | // Configures JsonSerializer to properly serialize NodaTime types. 85 | serializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); 86 | 87 | serializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; 88 | } 89 | 90 | if (useJsonProvider == JsonProvider.NewtonsoftJson) 91 | { 92 | services 93 | .AddMvcCore() 94 | .AddApiExplorer() 95 | .AddNewtonsoftJson(options => ConfigureNewtonsoftJsonSerializerSettings(options.SerializerSettings, shouldGenerateExamples: true)); 96 | } 97 | 98 | if (useJsonProvider == JsonProvider.SystemTextJson) 99 | { 100 | services 101 | .AddMvcCore() 102 | .AddApiExplorer() 103 | .AddJsonOptions(options => ConfigureSystemTextJsonSerializerSettings(options.JsonSerializerOptions, shouldGenerateExamples: true)) 104 | ; 105 | } 106 | 107 | //services.AddTransient, ConfigureNewtonsoftJsonJsonNamingPolicy>(); 108 | 109 | // Adds swagger 110 | services.AddSwaggerGen(c => 111 | { 112 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); 113 | 114 | if (useJsonProvider == JsonProvider.NewtonsoftJson) 115 | { 116 | // Configures swagger to use NodaTime with serializerSettings. 117 | c.ConfigureForNodaTime(configureSerializerSettings: ConfigureNewtonsoftJsonSerializerSettings); 118 | } 119 | 120 | if (useJsonProvider == JsonProvider.SystemTextJson) 121 | { 122 | JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(); 123 | ConfigureSystemTextJsonSerializerSettings(jsonSerializerOptions); 124 | c.ConfigureForNodaTimeWithSystemTextJson(jsonSerializerOptions); 125 | } 126 | }); 127 | } 128 | 129 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 130 | public void Configure(IApplicationBuilder app) 131 | { 132 | app.UseSwagger(); 133 | app.UseRouting(); 134 | app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); 135 | 136 | // Adds swagger UI 137 | app.UseSwaggerUI(c => 138 | { 139 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); 140 | }); 141 | } 142 | } 143 | 144 | public class NewtonsoftJsonNamingPolicy : JsonNamingPolicy 145 | { 146 | private readonly JsonSerializerSettings _jsonSerializerSettings; 147 | 148 | /// 149 | public NewtonsoftJsonNamingPolicy(JsonSerializerSettings jsonSerializerSettings) 150 | { 151 | _jsonSerializerSettings = jsonSerializerSettings; 152 | } 153 | 154 | /// 155 | public override string ConvertName(string name) 156 | { 157 | var contractResolver = _jsonSerializerSettings.ContractResolver; 158 | return (contractResolver as DefaultContractResolver)?.GetResolvedPropertyName(name) ?? name; 159 | } 160 | } 161 | 162 | ``` 163 | 164 | ## How it works 165 | 1. MicroElements.Swashbuckle.NodaTime creates Schemas for all NodaTime types 166 | 2. MicroElements.Swashbuckle.NodaTime configures JsonSerializer for examples 167 | 3. Maps types to [ISO 8601] 168 | 169 | ## Screenshots 170 | 171 | ## Without MicroElements.Swashbuckle.NodaTime 172 | ![](https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/master/images/NodaTime0.png) 173 | 174 | ## With MicroElements.Swashbuckle.NodaTime 175 | ![](https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/master/images/NodaTime1.png) 176 | 177 | ## With MicroElements.Swashbuckle.NodaTime (camelCase) 178 | ![](https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/master/images/NodaTime2.png) 179 | 180 | ## Build 181 | Windows: Run `build.ps1` 182 | 183 | Linux: Run `build.sh` 184 | 185 | ## License 186 | This project is licensed under the MIT license. See the [LICENSE] file for more info. 187 | 188 | [LICENSE]: https://raw.githubusercontent.com/micro-elements/MicroElements.Swashbuckle.NodaTime/master/LICENSE 189 | [ISO 8601]: https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14 190 | --------------------------------------------------------------------------------