├── .gitattributes ├── .github ├── FUNDING.yml └── workflows │ ├── build.yml │ └── pr.yml ├── .gitignore ├── .nuke ├── build.schema.json └── parameters.json ├── CONTRIBUTING.md ├── Directory.Build.props ├── Directory.Packages.props ├── LICENSE.md ├── README.md ├── assets ├── GitHubIcon.png ├── Icon.png └── NuGetIcon.png ├── build.cmd ├── build.ps1 ├── build.sh ├── build ├── .editorconfig ├── Build.CI.GitHubActions.cs ├── Build.Publish.cs ├── Build.cs ├── Configuration.cs ├── Directory.Build.props ├── Directory.Build.targets └── _build.csproj ├── global.json └── src ├── .editorconfig ├── NJsonSchema.Annotations ├── CanBeNullAttribute.cs ├── IJsonSchemaExtensionDataAttribute.cs ├── ItemsCanBeNullAttribute.cs ├── JsonFormatStrings.cs ├── JsonObjectType.cs ├── JsonSchemaAbstractAttribute.cs ├── JsonSchemaAttribute.cs ├── JsonSchemaDateAttribute.cs ├── JsonSchemaExtensionDataAttribute.cs ├── JsonSchemaFlattenAttribute.cs ├── JsonSchemaIgnoreAttribute.cs ├── JsonSchemaPatternPropertiesAttribute.cs ├── JsonSchemaProcessorAttribute.cs ├── JsonSchemaTypeAttribute.cs ├── MultipleOfAttribute.cs ├── NJsonSchema.Annotations.csproj ├── NJsonSchema.Annotations.nuspec ├── NotNullAttribute.cs └── NuGetIcon.png ├── NJsonSchema.Benchmark ├── CSharpTypeResolverBenchmark.cs ├── CsharpGeneratorBenchmark.cs ├── Directory.Build.props ├── JsonInheritanceConverterBenchmarks.cs ├── JsonSchemaBenchmark.cs ├── JsonSchemaGeneratorBenchmark.cs ├── LargeSchema.json ├── NJsonSchema.Benchmark.csproj ├── Program.cs ├── Schema.json ├── SchemaGenerationBenchmarks.cs ├── SerializationBenchmarks.cs └── TypeScriptGeneratorBenchmark.cs ├── NJsonSchema.CodeGeneration.CSharp.Tests ├── AbstractSchemaTests.cs ├── AdditionalPropertiesTests.cs ├── AllOfTests.cs ├── AnnotationsTests.cs ├── ArrayTests.cs ├── CSharpJsonSerializerGeneratorTests.cs ├── CodeCompiler.cs ├── DefaultPropertyTests.cs ├── DictionaryTests.cs ├── EnumTests.cs ├── GeneralGeneratorTests.cs ├── InheritanceInterfaceTests.cs ├── InheritanceTests.cs ├── InterfaceTests.cs ├── NJsonSchema.CodeGeneration.CSharp.Tests.csproj ├── NJsonSchema.CodeGeneration.CSharp.Tests.xml ├── NullableEnumTests.cs ├── NullableReferenceTypesTests.cs ├── NullableTests.cs ├── NumberTests.cs ├── ObjectPropertyRequiredTests.cs ├── ObsoleteTests.cs ├── References │ ├── A.json │ ├── Animal.json │ ├── B.json │ ├── C.json │ ├── D.json │ ├── E.json │ ├── F.json │ └── G.json ├── ReferencesTest.cs ├── Snapshots │ ├── ValidationAttributesTests.When_array_property_has_maxitems_then_maxlength_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_array_property_has_minitems_then_minlength_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_int32_property_has_minimum_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_int64_property_has_minimum_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_int_property_has_maximum_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_integer_property_has_minimum_and_maximum_that_are_int64_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_integer_property_has_minimum_and_maximum_that_are_too_large_or_small_for_int64.verified.txt │ ├── ValidationAttributesTests.When_integer_property_has_minimum_and_maximum_with_exclusive_true_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_number_property_has_minimum_and_maximum_that_are_decimal_then_range_attribute_is_rendered.verified.txt │ ├── ValidationAttributesTests.When_number_property_has_minimum_and_maximum_that_are_double_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_number_property_has_minimum_and_maximum_with_exclusive_true_and_multipleof_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_string_property_has_maxlength_then_stringlength_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_string_property_has_minlength_then_stringlength_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValidationAttributesTests.When_string_property_has_pattern_then_regularexpression_attribute_is_rendered_in_Swagger_mode.verified.txt │ ├── ValueGeneratorTests.When_property_is_string_and_format_is_date_time_then_assign_default_value.verified.txt │ └── ValueGeneratorTests.When_schema_contains_range_then_code_is_correctly_generated.verified.txt ├── StringPropertyRequiredTests.cs ├── UriTests.cs ├── ValidationAttributesTests.cs └── ValueGeneratorTests.cs ├── NJsonSchema.CodeGeneration.CSharp ├── CSharpClassStyle.cs ├── CSharpGenerator.cs ├── CSharpGeneratorSettings.cs ├── CSharpJsonLibrary.cs ├── CSharpJsonPolymorphicSerializationStyle.cs ├── CSharpJsonSerializerGenerator.cs ├── CSharpPropertyNameGenerator.cs ├── CSharpTypeResolver.cs ├── CSharpValueGenerator.cs ├── Models │ ├── ClassTemplateModel.cs │ ├── DateFormatConverterTemplateModel.cs │ ├── EnumTemplateModel.cs │ ├── FileTemplateModel.cs │ ├── JsonInheritanceConverterTemplateModel.cs │ └── PropertyModel.cs ├── NJsonSchema.CodeGeneration.CSharp.csproj ├── NJsonSchema.CodeGeneration.CSharp.nuspec ├── NuGetIcon.png └── Templates │ ├── Class.Annotations.liquid │ ├── Class.Body.liquid │ ├── Class.Constructor.Record.liquid │ ├── Class.Constructor.liquid │ ├── Class.FromJson.liquid │ ├── Class.Inheritance.liquid │ ├── Class.Inpc.liquid │ ├── Class.Property.Annotations.liquid │ ├── Class.ToJson.liquid │ ├── Class.liquid │ ├── DateFormatConverter.liquid │ ├── Enum.Annotations.liquid │ ├── Enum.Member.Annotations.liquid │ ├── Enum.liquid │ ├── File.liquid │ ├── JsonInheritanceAttribute.liquid │ └── JsonInheritanceConverter.liquid ├── NJsonSchema.CodeGeneration.Tests ├── ApiSurfaceGuard.cs ├── DefaultGenerationTests.cs ├── DefaultValueGeneratorTests.cs ├── EnumGenerationTests.cs ├── InheritanceSerializationTests.cs ├── LiquidTests.cs ├── NJsonSchema.CodeGeneration.Tests.csproj ├── Samples │ └── SampleTests.cs ├── TemplateFactoryTests.cs ├── Templates │ ├── elseif.liquid │ └── inline-liquid.liquid └── VerifyHelper.cs ├── NJsonSchema.CodeGeneration.TypeScript.Tests ├── AbstractGenerationTests.cs ├── ClassGenerationTests.cs ├── ClassOrderTests.cs ├── CodeCompiler.cs ├── ConstructorInterfaceTests.cs ├── DateCodeGenerationTests.cs ├── DateTimeCodeGenerationTests.cs ├── DictionaryTests.cs ├── ExtensionCodeTests.cs ├── InheritanceTests.cs ├── Models │ ├── Address.cs │ ├── File.cs │ ├── Gender.cs │ ├── Person.cs │ └── Teacher.cs ├── NJsonSchema.CodeGeneration.TypeScript.Tests.csproj ├── NJsonSchema.CodeGeneration.TypeScript.Tests.xml ├── NullabilityTests.cs ├── PropertyNameTests.cs ├── Snapshots │ ├── ClassGenerationTests.Verify_output_style=Class_version=1.8.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Class_version=2.1.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Class_version=2.7.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Class_version=4.3.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Interface_version=1.8.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Interface_version=2.1.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Interface_version=2.7.verified.txt │ ├── ClassGenerationTests.Verify_output_style=Interface_version=4.3.verified.txt │ ├── ClassGenerationTests.Verify_output_style=KnockoutClass_version=1.8.verified.txt │ ├── ClassGenerationTests.Verify_output_style=KnockoutClass_version=2.1.verified.txt │ ├── ClassGenerationTests.Verify_output_style=KnockoutClass_version=2.7.verified.txt │ ├── ClassGenerationTests.Verify_output_style=KnockoutClass_version=4.3.verified.txt │ ├── PropertyNameTests.When_class_has_restricted_properties_they_are_escaped.verified.txt │ ├── TypeScriptDiscriminatorTests.When_generating_interface_contract_add_discriminator.verified.txt │ ├── TypeScriptDiscriminatorTests.When_generating_interface_contract_add_discriminator_string_literal.verified.txt │ ├── TypeScriptDiscriminatorTests.When_parameter_is_abstract_then_generate_union_class.verified.txt │ └── TypeScriptDiscriminatorTests.When_parameter_is_abstract_then_generate_union_interface.verified.txt ├── TypeScriptDictionaryTests.cs ├── TypeScriptDiscriminatorTests.cs ├── TypeScriptGeneratorTests.cs ├── TypeScriptObjectTests.cs ├── package-lock.json ├── package.json └── tsconfig.json ├── NJsonSchema.CodeGeneration.TypeScript ├── DataConversionGenerator.cs ├── DataConversionParameters.cs ├── Models │ ├── ClassTemplateModel.cs │ ├── EnumTemplateModel.cs │ ├── FileTemplateModel.cs │ └── PropertyModel.cs ├── NJsonSchema.CodeGeneration.TypeScript.csproj ├── NJsonSchema.CodeGeneration.TypeScript.nuspec ├── NuGetIcon.png ├── Templates │ ├── Class.liquid │ ├── ConvertToClass.liquid │ ├── ConvertToJavaScript.liquid │ ├── Enum.StringLiteral.liquid │ ├── Enum.liquid │ ├── File.FormatDate.liquid │ ├── File.ParseDateOnly.liquid │ ├── File.ReferenceHandling.liquid │ ├── File.liquid │ ├── Interface.liquid │ └── KnockoutClass.liquid ├── TypeScriptDateTimeType.cs ├── TypeScriptEnumStyle.cs ├── TypeScriptExtensionCode.cs ├── TypeScriptGenerator.cs ├── TypeScriptGeneratorSettings.cs ├── TypeScriptNullValue.cs ├── TypeScriptPropertyNameGenerator.cs ├── TypeScriptTypeResolver.cs ├── TypeScriptTypeStyle.cs └── TypeScriptValueGenerator.cs ├── NJsonSchema.CodeGeneration ├── CodeArtifact.cs ├── CodeArtifactCategory.cs ├── CodeArtifactExtensions.cs ├── CodeArtifactLanguage.cs ├── CodeArtifactType.cs ├── CodeGeneratorSettingsBase.cs ├── DefaultEnumNameGenerator.cs ├── DefaultTemplateFactory.cs ├── ExtensionCode.cs ├── GeneratorBase.cs ├── IEnumNameGenerator.cs ├── IPropertyNameGenerator.cs ├── ITemplate.cs ├── ITemplateFactory.cs ├── JsonSchemaGraphUtilities.cs ├── LiquidParser.cs ├── Models │ ├── ClassTemplateModelBase.cs │ ├── EnumerationItemModel.cs │ └── PropertyModelBase.cs ├── NJsonSchema.CodeGeneration.csproj ├── NJsonSchema.CodeGeneration.nuspec ├── NuGetIcon.png ├── TypeResolverBase.cs └── ValueGeneratorBase.cs ├── NJsonSchema.Demo.Performance ├── NJsonSchema.Demo.Performance.csproj └── Program.cs ├── NJsonSchema.Demo ├── NJsonSchema.Demo.csproj ├── Program.cs └── Tests │ ├── additionalItems.json │ ├── additionalProperties.json │ ├── allOf.json │ ├── anyOf.json │ ├── default.json │ ├── definitions.json │ ├── dependencies.json │ ├── enum.json │ ├── items.json │ ├── maxItems.json │ ├── maxLength.json │ ├── maxProperties.json │ ├── maximum.json │ ├── minItems.json │ ├── minLength.json │ ├── minProperties.json │ ├── minimum.json │ ├── multipleOf.json │ ├── not.json │ ├── oneOf.json │ ├── optional │ ├── bignum.json │ ├── format.json │ └── zeroTerminatedFloats.json │ ├── pattern.json │ ├── patternProperties.json │ ├── properties.json │ ├── ref.json │ ├── refRemote.json │ ├── required.json │ ├── type.json │ └── uniqueItems.json ├── NJsonSchema.NewtonsoftJson.Tests ├── Generation │ ├── RecordTests.cs │ └── StructTests.cs └── NJsonSchema.NewtonsoftJson.Tests.csproj ├── NJsonSchema.NewtonsoftJson ├── Converters │ ├── JsonExceptionConverter.cs │ ├── JsonInheritanceAttribute.cs │ ├── JsonInheritanceConverter.cs │ └── JsonReferenceConverter.cs ├── Generation │ ├── NewtonsoftJsonReflectionService.cs │ ├── NewtonsoftJsonSchemaGenerator.cs │ └── NewtonsoftJsonSchemaGeneratorSettings.cs ├── NJsonSchema.NewtonsoftJson.csproj └── NuGetIcon.png ├── NJsonSchema.Tests ├── Conversion │ ├── ArrayTypeToSchemaTests.cs │ ├── SchemaReferenceTests.cs │ └── TypeToSchemaTests.cs ├── Converters │ └── JsonExceptionConverterTests.cs ├── Generation │ ├── AbstractGenerationTests.cs │ ├── AllowAdditionalPropertiesTests.cs │ ├── AnnotationsGenerationTests.cs │ ├── ArrayGenerationTests.cs │ ├── AttributeGenerationTests.cs │ ├── AttributeGenerationTestsResources.Designer.cs │ ├── AttributeGenerationTestsResources.resx │ ├── ContractResolverTests.cs │ ├── DataContractTests.cs │ ├── DefaultReflectionServiceTests.cs │ ├── DefaultSchemaNameGeneratorTests.cs │ ├── DefaultTypeNameGeneratorTests.cs │ ├── DictionaryTests.cs │ ├── EnumGenerationTests.cs │ ├── EnumTests.cs │ ├── ExceptionTypeTests.cs │ ├── ExcplicitInterfacePropertyTests.cs │ ├── ExtensionDataGenerationTests.cs │ ├── FieldGenerationTests.cs │ ├── FlattenInheritanceHierarchyTests.cs │ ├── GenericTests.cs │ ├── IgnoredPropertyTests.cs │ ├── InheritanceTests.cs │ ├── InterfaceTests.cs │ ├── JsonInheritanceConverterTests.cs │ ├── JsonPropertyAttributeTests.cs │ ├── JsonSchemaExtensionDataAttributeGeneratorTests.cs │ ├── JsonSchemaTypeAttributeTests.cs │ ├── KnownTypeGenerationTests.cs │ ├── NullPropertyTests.cs │ ├── PrimitiveTypeGenerationTests.cs │ ├── PropertyNamesGenerationTests.cs │ ├── RecordTests.cs │ ├── SampleJsonDataGeneratorTests.cs │ ├── SampleJsonSchemaGeneratorTests.cs │ ├── SchemaGenerationTests.cs │ ├── SchemaProcessorTests.cs │ ├── ShouldSerializeTests.cs │ ├── SystemTextJson │ │ ├── SystemTextJsonExtensionDataGenerationTests.cs │ │ ├── SystemTextJsonInheritanceTests.cs │ │ ├── SystemTextJsonOptionsConverterTests.cs │ │ └── SystemTextJsonTests.cs │ ├── TypeMapperTests.cs │ ├── XmlDocsTests.cs │ └── XmlObjectTests.cs ├── Infrastructure │ └── PropertyRenameAndIgnoreSerializerContractResolverTests.cs ├── NJsonSchema.Tests.csproj ├── References │ ├── LocalReferencesTests.cs │ └── LocalReferencesTests │ │ ├── animal.json │ │ ├── collection.json │ │ ├── dir_with_# │ │ ├── first.json │ │ └── second.json │ │ ├── schema_with_collection_reference.json │ │ ├── schema_with_indirect_reference.json │ │ ├── schema_with_indirect_subreference.json │ │ └── schema_with_reference.json ├── Schema │ ├── DataContractTests.cs │ ├── JsonPathUtilitiesGetJsonPathTests.cs │ ├── JsonPathUtilitiesGetObjectFromJsonPathTests.cs │ └── JsonSchemaTests.cs ├── Serialization │ ├── AllowAdditionalPropertiesTests.cs │ ├── DiscriminatorSerializationTests.cs │ └── ExtensionDataTests.cs └── Validation │ ├── ArrayValidationTests.cs │ ├── CustomValidationTests.cs │ ├── EnumValidationTests.cs │ ├── FormatBase64Tests.cs │ ├── FormatDateTests.cs │ ├── FormatDateTimeTests.cs │ ├── FormatEmailTests.cs │ ├── FormatGuidTests.cs │ ├── FormatHostnameTests.cs │ ├── FormatIpV4Tests.cs │ ├── FormatIpV6Tests.cs │ ├── FormatTimeSpanTests.cs │ ├── FormatTimeTests.cs │ ├── FormatUriTests.cs │ ├── FormatUuidTests.cs │ ├── InheritanceTests.cs │ ├── LineInformationTest.cs │ ├── NullPropertyTests.cs │ ├── NumberTests.cs │ ├── ObjectValidationTests.cs │ ├── OneOfValidationTests.cs │ ├── PatternPropertyValidationTests.cs │ ├── SchemaTests.cs │ ├── UniqueItemsTests.cs │ └── ValueTypeValidationTests.cs ├── NJsonSchema.Yaml.Tests ├── NJsonSchema.Yaml.Tests.csproj └── References │ ├── YamlReferencesTest │ ├── collection.json │ ├── collection.yaml │ ├── common-items │ │ ├── headers.yaml │ │ ├── parameters.yaml │ │ ├── responses.yaml │ │ └── schemas.yaml │ ├── json_schema_with_json_reference.json │ ├── json_schema_with_yaml_reference.json │ ├── subdir_spec │ │ ├── enums │ │ │ └── TaskExecutionStatusEnum.yaml │ │ ├── models │ │ │ ├── ExecuteTaskResultModel.yaml │ │ │ ├── LifeCycleCollectionModel.yaml │ │ │ └── LifeCycleModel.yaml │ │ └── yaml_spec_with_yaml_schema_with_relative_subdir_refs.yaml │ ├── yaml_schema_with_json_reference.yaml │ ├── yaml_schema_with_yaml_reference.yaml │ └── yaml_spec_with_yaml_schema_refs.yaml │ └── YamlReferencesTests.cs ├── NJsonSchema.Yaml ├── JsonAndYamlReferenceResolver.cs ├── JsonSchemaYaml.cs ├── NJsonSchema.Yaml.csproj └── NuGetIcon.png ├── NJsonSchema.sln ├── NJsonSchema.snk └── NJsonSchema ├── Collections ├── ObservableCollectionExtensions.cs └── ObservableDictionary.cs ├── CompilerFeatures.cs ├── ConversionUtilities.cs ├── Converters ├── JsonInheritanceAttribute.cs └── JsonInheritanceConverter.cs ├── DefaultTypeNameGenerator.cs ├── Generation ├── DefaultSchemaNameGenerator.cs ├── IReflectionService.cs ├── ISchemaNameGenerator.cs ├── ISchemaProcessor.cs ├── IXmlDocsSettings.cs ├── JsonSchemaGenerator.cs ├── JsonSchemaGeneratorSettings.cs ├── JsonSchemaResolver.cs ├── JsonTypeDescription.cs ├── ReferenceTypeNullHandling.cs ├── ReflectionServiceBase.cs ├── SampleJsonDataGenerator.cs ├── SchemaProcessorContext.cs ├── SchemaProcessors │ └── DiscriminatorSchemaProcessor.cs ├── SystemTextJsonReflectionService.cs ├── SystemTextJsonSchemaGeneratorSettings.cs ├── TypeMappers │ ├── ITypeMapper.cs │ ├── ObjectTypeMapper.cs │ ├── PrimitiveTypeMapper.cs │ └── TypeMapperContext.cs └── XmlDocsSettingsExtensions.cs ├── IDocumentPathProvider.cs ├── IJsonExtensionObject.cs ├── ITypeNameGenerator.cs ├── Infrastructure ├── DynamicApis.cs ├── EnumExtensions.cs ├── IgnoreEmptyCollectionsContractResolver.cs ├── JsonSchemaSerialization.cs ├── Polyfills.cs ├── PropertyRenameAndIgnoreSerializerContractResolver.cs ├── TypeExtensions.cs └── XmlObjectExtension.cs ├── JsonExtensionObject.cs ├── JsonPathUtilities.cs ├── JsonReferenceResolver.cs ├── JsonSchema.Reference.cs ├── JsonSchema.Serialization.cs ├── JsonSchema.cs ├── JsonSchemaAppender.cs ├── JsonSchemaProperty.cs ├── JsonSchemaReferenceUtilities.cs ├── JsonXmlObject.cs ├── NJsonSchema.csproj ├── NJsonSchema.nuspec ├── NuGetIcon.png ├── OpenApiDiscriminator.cs ├── References ├── IJsonReference.cs ├── IJsonReferenceBase.cs ├── JsonReferenceBase.cs └── JsonReferenceExtensions.cs ├── SampleJsonDataGeneratorSettings.cs ├── SampleJsonSchemaGenerator.cs ├── SampleJsonSchemaGeneratorSettings.cs ├── SchemaType.cs ├── Validation ├── ChildSchemaValidationError.cs ├── FormatValidators │ ├── Base64FormatValidator.cs │ ├── ByteFormatValidator.cs │ ├── DateFormatValidator.cs │ ├── DateTimeFormatValidator.cs │ ├── EmailFormatValidator.cs │ ├── GuidFormatValidator.cs │ ├── HostnameFormatValidator.cs │ ├── IFormatValidator.cs │ ├── IpV4FormatValidator.cs │ ├── IpV6FormatValidator.cs │ ├── TimeFormatValidator.cs │ ├── TimeSpanFormatValidator.cs │ ├── UriFormatValidator.cs │ └── UuidFormatValidator.cs ├── JsonSchemaValidator.cs ├── JsonSchemaValidatorOptions.cs ├── MultiTypeValidationError.cs ├── ValidationError.cs └── ValidationErrorKind.cs ├── ValueStringBuilder.cs ├── Visitors ├── AsyncJsonReferenceVisitorBase.cs ├── AsyncJsonSchemaVisitorBase.cs ├── JsonReferenceVisitorBase.cs └── JsonSchemaVisitorBase.cs └── app.config /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: RicoSuter 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/bin/** 2 | **/obj/** 3 | src/packages/Newtonsoft.Json** 4 | 5 | **.suo 6 | **.user 7 | **.DotSettings 8 | 9 | **.sln.ide/** 10 | **.vs/** 11 | .vscode/ 12 | .idea/ 13 | 14 | /src/NJsonSchema.sln.GhostDoc.xml 15 | 16 | [Bb]in/ 17 | [Oo]bj/ 18 | /src/packages 19 | .vs 20 | /src/NJsonSchema.CodeGeneration.Tests2 21 | *.vspx 22 | /src/TestResults 23 | /src/.cr/* 24 | /src/NJsonSchema.Benchmark/BenchmarkDotNet.Artifacts* 25 | _ReSharper.Caches 26 | /.nuke/temp 27 | /artifacts 28 | 29 | node_modules 30 | -------------------------------------------------------------------------------- /.nuke/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./build.schema.json", 3 | "Solution": "src/NJsonSchema.sln" 4 | } -------------------------------------------------------------------------------- /Directory.Packages.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Rico Suter 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | 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, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /assets/GitHubIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/assets/GitHubIcon.png -------------------------------------------------------------------------------- /assets/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/assets/Icon.png -------------------------------------------------------------------------------- /assets/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/assets/NuGetIcon.png -------------------------------------------------------------------------------- /build.cmd: -------------------------------------------------------------------------------- 1 | :; set -eo pipefail 2 | :; SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) 3 | :; ${SCRIPT_DIR}/build.sh "$@" 4 | :; exit $? 5 | 6 | @ECHO OFF 7 | powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0build.ps1" %* 8 | -------------------------------------------------------------------------------- /build/.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | dotnet_style_qualification_for_field = false:warning 3 | dotnet_style_qualification_for_property = false:warning 4 | dotnet_style_qualification_for_method = false:warning 5 | dotnet_style_qualification_for_event = false:warning 6 | dotnet_style_require_accessibility_modifiers = never:warning 7 | 8 | csharp_style_expression_bodied_methods = true:silent 9 | csharp_style_expression_bodied_properties = true:warning 10 | csharp_style_expression_bodied_indexers = true:warning 11 | csharp_style_expression_bodied_accessors = true:warning 12 | -------------------------------------------------------------------------------- /build/Configuration.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using Nuke.Common.Tooling; 3 | 4 | [TypeConverter(typeof(TypeConverter))] 5 | public class Configuration : Enumeration 6 | { 7 | public static Configuration Debug = new Configuration { Value = nameof(Debug) }; 8 | public static Configuration Release = new Configuration { Value = nameof(Release) }; 9 | 10 | public static implicit operator string(Configuration configuration) 11 | { 12 | return configuration.Value; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /build/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build/Directory.Build.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build/_build.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net9.0 6 | 7 | CS0649;CS0169 8 | .. 9 | .. 10 | 1 11 | true 12 | true 13 | true 14 | false 15 | true 16 | false 17 | false 18 | true 19 | true 20 | true 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "9.0.100", 4 | "rollForward": "latestMinor" 5 | } 6 | } -------------------------------------------------------------------------------- /src/.editorconfig: -------------------------------------------------------------------------------- 1 | ; What is EditorConfig? http://editorconfig.org/ 2 | 3 | root = true 4 | 5 | ; general settings 6 | [*] 7 | indent_style = space 8 | indent_size = 4 9 | end_of_line = crlf 10 | insert_final_newline = false 11 | -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/CanBeNullAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Indicates that the value of the marked element is nullable. 12 | [AttributeUsage( 13 | AttributeTargets.Method | 14 | AttributeTargets.Parameter | 15 | AttributeTargets.Property | 16 | AttributeTargets.ReturnValue | 17 | AttributeTargets.Delegate | 18 | AttributeTargets.Field | 19 | AttributeTargets.Event)] 20 | public class CanBeNullAttribute : Attribute 21 | { 22 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/IJsonSchemaExtensionDataAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Interface to add an extension data property to a class or property, implementation needs to inherit from System.Attribute. 12 | #pragma warning disable CA1711 // Rename type name IJsonSchemaExtensionDataAttribute so that it does not end in 'Attribute' 13 | public interface IJsonSchemaExtensionDataAttribute 14 | #pragma warning restore CA1711 15 | { 16 | /// Gets the extension data. 17 | IReadOnlyDictionary ExtensionData { get; } 18 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/ItemsCanBeNullAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Annotation to specify that array items or dictionary values are nullable. 12 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue | 13 | AttributeTargets.Field)] 14 | public class ItemsCanBeNullAttribute : Attribute 15 | { 16 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/JsonObjectType.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema; 2 | 3 | /// 4 | /// Enumeration of the possible object types. 5 | /// 6 | /// Keep in sync with NJsonSchema.JsonObjectType 7 | /// 8 | [Flags] 9 | public enum JsonObjectType 10 | { 11 | /// No object type. 12 | None = 0, 13 | 14 | /// An array. 15 | Array = 1, 16 | 17 | /// A boolean value. 18 | Boolean = 2, 19 | 20 | /// An integer value. 21 | Integer = 4, 22 | 23 | /// A null. 24 | Null = 8, 25 | 26 | /// An number value. 27 | Number = 16, 28 | 29 | /// An object. 30 | Object = 32, 31 | 32 | /// A string. 33 | String = 64, 34 | 35 | /// A file (used in Swagger specifications). 36 | File = 128, 37 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/JsonSchemaAbstractAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Annotation to merge all inherited properties into this class/schema. 12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] 13 | public class JsonSchemaAbstractAttribute : Attribute 14 | { 15 | /// Initializes a new instance of the class. 16 | public JsonSchemaAbstractAttribute() 17 | { 18 | IsAbstract = true; 19 | } 20 | 21 | /// Initializes a new instance of the class. 22 | /// The explicit flag to override the global setting (i.e. disable the generation for a type). 23 | public JsonSchemaAbstractAttribute(bool isAbstract) 24 | { 25 | IsAbstract = isAbstract; 26 | } 27 | 28 | /// Gets or sets a value indicating whether to set the x-abstract property for given type. 29 | public bool IsAbstract { get; } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/JsonSchemaDateAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Annotation to mark a property or class as string type with format 'date'. 12 | public class JsonSchemaDateAttribute : JsonSchemaAttribute 13 | { 14 | /// Initializes a new instance of the class. 15 | public JsonSchemaDateAttribute() 16 | : base(JsonObjectType.String) 17 | { 18 | Format = JsonFormatStrings.Date; 19 | } 20 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/JsonSchemaFlattenAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Annotation to merge all inherited properties into this class/schema. 12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] 13 | public class JsonSchemaFlattenAttribute : Attribute 14 | { 15 | /// Initializes a new instance of the class. 16 | public JsonSchemaFlattenAttribute() 17 | { 18 | Flatten = true; 19 | } 20 | 21 | /// Initializes a new instance of the class. 22 | /// The explicit flag to override the global setting (i.e. disable the generation for a type). 23 | public JsonSchemaFlattenAttribute(bool flatten) 24 | { 25 | Flatten = flatten; 26 | } 27 | 28 | /// Gets or sets a value indicating whether to flatten the given type. 29 | public bool Flatten { get; } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/JsonSchemaIgnoreAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Indicates that the marked class is ignored during the JSON Schema generation. 12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] 13 | public class JsonSchemaIgnoreAttribute : Attribute 14 | { 15 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/JsonSchemaProcessorAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/NSwag/NSwag/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Registers an schema processor for the given class. 12 | /// 13 | [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] 14 | public class JsonSchemaProcessorAttribute : Attribute 15 | { 16 | /// Initializes a new instance of the class. 17 | /// The schema processor type (must implement ISchemaProcessor). 18 | /// The parameters. 19 | public JsonSchemaProcessorAttribute(Type type, params object[] parameters) 20 | { 21 | Type = type; 22 | Parameters = parameters; 23 | } 24 | 25 | /// Gets or sets the type of the operation processor (must implement ISchemaProcessor). 26 | public Type Type { get; set; } 27 | 28 | /// Gets or sets the type of the constructor parameters. 29 | public object[] Parameters { get; set; } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/MultipleOfAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Attribute to set the multipleOf parameter of a JSON Schema. 12 | [AttributeUsage(AttributeTargets.Property)] 13 | public class MultipleOfAttribute : Attribute 14 | { 15 | /// Initializes a new instance of the class. 16 | /// The multipleOf value. 17 | public MultipleOfAttribute(double multipleOf) 18 | { 19 | MultipleOf = (decimal) multipleOf; 20 | } 21 | 22 | /// Initializes a new instance of the class. 23 | /// The multipleOf value. 24 | public MultipleOfAttribute(decimal multipleOf) 25 | { 26 | MultipleOf = multipleOf; 27 | } 28 | 29 | /// Gets the value whose modulo the the JSON value must be zero. 30 | public decimal MultipleOf { get; private set; } 31 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/NJsonSchema.Annotations.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net462 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/NJsonSchema.Annotations.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $author$ 7 | $description$ 8 | json schema validation generator .net 9 | http://NJsonSchema.org 10 | MIT 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/NotNullAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Annotations; 10 | 11 | /// Indicates that the value of the marked element could never be null. 12 | [AttributeUsage( 13 | AttributeTargets.Method | 14 | AttributeTargets.Parameter | 15 | AttributeTargets.Property | 16 | AttributeTargets.ReturnValue | 17 | AttributeTargets.Delegate | 18 | AttributeTargets.Field | 19 | AttributeTargets.Event)] 20 | public class NotNullAttribute : Attribute 21 | { 22 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Annotations/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.Annotations/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/CSharpTypeResolverBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using NJsonSchema.CodeGeneration.CSharp; 3 | 4 | namespace NJsonSchema.Benchmark; 5 | 6 | [MemoryDiagnoser] 7 | public class CSharpTypeResolverBenchmark 8 | { 9 | private Dictionary _definitions; 10 | private CSharpGeneratorSettings _settings; 11 | 12 | [GlobalSetup] 13 | public async Task Setup() 14 | { 15 | var json = await JsonSchemaBenchmark.ReadJson(); 16 | var schema = await JsonSchema.FromJsonAsync(json); 17 | _definitions = schema.Definitions.ToDictionary(p => p.Key, p => p.Value); 18 | _settings = new CSharpGeneratorSettings(); 19 | } 20 | 21 | [Benchmark] 22 | public void RegisterSchemaDefinitions() 23 | { 24 | var resolver = new CSharpTypeResolver(_settings, exceptionSchema: null); 25 | resolver.RegisterSchemaDefinitions(_definitions); 26 | } 27 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/CsharpGeneratorBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using NJsonSchema.CodeGeneration.CSharp; 3 | 4 | namespace NJsonSchema.Benchmark 5 | { 6 | [MemoryDiagnoser] 7 | public class CsharpGeneratorBenchmark 8 | { 9 | private string _json; 10 | private JsonSchema _schema; 11 | 12 | [GlobalSetup] 13 | public async Task Setup() 14 | { 15 | _json = await JsonSchemaBenchmark.ReadJson(); 16 | _schema = await JsonSchema.FromJsonAsync(_json); 17 | } 18 | 19 | [Benchmark] 20 | public void GenerateFile() 21 | { 22 | var generator = new CSharpGenerator(_schema, new CSharpGeneratorSettings()); 23 | generator.GenerateFile(); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/JsonSchemaBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace NJsonSchema.Benchmark 4 | { 5 | [MemoryDiagnoser] 6 | public class JsonSchemaBenchmark 7 | { 8 | private string _json; 9 | 10 | [GlobalSetup] 11 | public async Task Setup() 12 | { 13 | _json = await ReadJson(); 14 | } 15 | 16 | internal static Task ReadJson() 17 | { 18 | var assembly = typeof(JsonSchemaBenchmark).Assembly; 19 | var file = assembly.GetManifestResourceNames().First(x => x.Contains("LargeSchema.json")); 20 | return new StreamReader(assembly.GetManifestResourceStream(file)).ReadToEndAsync(); 21 | } 22 | 23 | [Benchmark] 24 | public Task FromJsonAsync() 25 | { 26 | return JsonSchema.FromJsonAsync(_json); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/JsonSchemaGeneratorBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | 4 | namespace NJsonSchema.Benchmark 5 | { 6 | [MemoryDiagnoser] 7 | public class JsonSchemaGeneratorBenchmark 8 | { 9 | [Benchmark] 10 | public void GenerateFile() 11 | { 12 | NewtonsoftJsonSchemaGenerator.FromType(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/NJsonSchema.Benchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | false 6 | $(NoWarn),xUnit1013;CS1591 7 | false 8 | disable 9 | false 10 | enable 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NJsonSchema.Benchmark 4 | { 5 | public static class Program 6 | { 7 | public static void Main(string[] args) 8 | { 9 | // RunCsharpBenchmark(); 10 | BenchmarkDotNet.Running.BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).RunAllJoined(); 11 | } 12 | 13 | #pragma warning disable IDE0051 14 | private static void RunCsharpBenchmark() 15 | #pragma warning restore IDE0051 16 | { 17 | var benchmark = new CsharpGeneratorBenchmark(); 18 | benchmark.Setup().GetAwaiter().GetResult(); 19 | benchmark.GenerateFile(); 20 | RunCode(benchmark); 21 | } 22 | 23 | [MethodImpl(MethodImplOptions.NoInlining)] 24 | private static void RunCode(CsharpGeneratorBenchmark benchmark) 25 | { 26 | for (int i = 0; i < 100; ++i) 27 | { 28 | benchmark.GenerateFile(); 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/Schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-04/schema#", 3 | "properties": { 4 | "some_property": { 5 | "description": "Example property", 6 | "type": "string", 7 | "maxLength": 64 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Benchmark/TypeScriptGeneratorBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using NJsonSchema.CodeGeneration.TypeScript; 3 | 4 | namespace NJsonSchema.Benchmark 5 | { 6 | [MemoryDiagnoser] 7 | public class TypeScriptGeneratorBenchmark 8 | { 9 | private string _json; 10 | private JsonSchema _schema; 11 | 12 | [GlobalSetup] 13 | public async Task Setup() 14 | { 15 | _json = await JsonSchemaBenchmark.ReadJson(); 16 | _schema = await JsonSchema.FromJsonAsync(_json); 17 | } 18 | 19 | [Benchmark] 20 | public void GenerateFile() 21 | { 22 | var generator = new TypeScriptGenerator(_schema, new TypeScriptGeneratorSettings()); 23 | generator.GenerateFile(); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/AbstractSchemaTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.CodeGeneration.CSharp; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | 4 | namespace NJsonSchema.CodeGeneration.Tests.CSharp.Generation 5 | { 6 | public class AbstractSchemaTests 7 | { 8 | public abstract class AbstractClass 9 | { 10 | public string Foo { get; set; } 11 | } 12 | 13 | [Fact] 14 | public void When_class_is_abstract_then_is_abstract_CSharp_keyword_is_generated() 15 | { 16 | // Arrange 17 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 18 | 19 | // Act 20 | var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); 21 | var code = generator.GenerateFile("AbstractClass"); 22 | 23 | // Assert 24 | Assert.Contains("public abstract partial class AbstractClass", code); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/NJsonSchema.CodeGeneration.CSharp.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | $(TargetFrameworks);net472 6 | false 7 | disable 8 | latest-Minimal 9 | $(NoWarn);1591 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/NJsonSchema.CodeGeneration.CSharp.Tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NJsonSchema.CodeGeneration.CSharp.Tests 5 | 6 | 7 | 8 | 9 | Foobar. 10 | 11 | 12 | 13 | 14 | Foobar. 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableEnumTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.CodeGeneration.CSharp; 2 | 3 | namespace NJsonSchema.CodeGeneration.Tests.CSharp 4 | { 5 | public class NullableEnumTests 6 | { 7 | [Fact] 8 | public async Task When_Swagger2_enum_property_is_not_required_then_it_is_nullable() 9 | { 10 | var json = 11 | @"{ 12 | ""properties"": { 13 | ""sex"": { 14 | ""$ref"": ""#/definitions/Sex"" 15 | } 16 | }, 17 | ""definitions"": { 18 | ""Sex"": { 19 | ""type"": ""string"", 20 | ""enum"": [ 21 | ""male"", 22 | ""female"" 23 | ] 24 | } 25 | } 26 | }"; 27 | 28 | var schema = await JsonSchema.FromJsonAsync(json); 29 | var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings 30 | { 31 | SchemaType = SchemaType.Swagger2, 32 | ClassStyle = CSharpClassStyle.Poco 33 | }); 34 | 35 | // Act 36 | var code = generator.GenerateFile("MyClass"); 37 | 38 | // Assert 39 | Assert.Contains(@"public Sex? Sex", code); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/A.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "required": [ 4 | "signalPaths" 5 | ], 6 | "description": "This is the class A", 7 | "properties": { 8 | "type": { 9 | "$ref": "./C.json", 10 | "description": "This is the type of A" 11 | }, 12 | "signalPaths": { 13 | "children": "array", 14 | "items": { 15 | "$ref": "./B.json", 16 | "description": "This is a list of children" 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/Animal.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Animal", 3 | "type": "object", 4 | "x-abstract": true, 5 | "discriminator": "discriminator", 6 | 7 | "definitions": { 8 | "Cat": { 9 | "type": "object", 10 | "allOf": [ 11 | { 12 | "$ref": "Animal.json" 13 | } 14 | ] 15 | }, 16 | "PersianCat": { 17 | "type": "object", 18 | "allOf": [ 19 | { 20 | "$ref": "#/definitions/Cat" 21 | } 22 | ] 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/B.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "description": "This is the class B", 4 | "properties": { 5 | "id": { 6 | "type": "string", 7 | "description": "This is the ID of B" 8 | }, 9 | "type": { 10 | "$ref": "./C.json", 11 | "description": "This is the type of B" 12 | }, 13 | "empty": { 14 | "$ref": "./D.json", 15 | "description": "This one should be of type D and not object" 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/C.json: -------------------------------------------------------------------------------- 1 | { 2 | "type":"string", 3 | "description":"Possible types", 4 | "enum":[ 5 | "First", 6 | "Second" 7 | ] 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/D.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "description": "Possible types" 4 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/E.json: -------------------------------------------------------------------------------- 1 | { 2 | "definitions": { 3 | "B": { 4 | "type": "object", 5 | "description": "This is the class B", 6 | "properties": { 7 | "id": { 8 | "type": "string", 9 | "description": "This is the ID of B" 10 | }, 11 | "type": { 12 | "$ref": "#/definitions/C", 13 | "description": "This is the type of B" 14 | }, 15 | "empty": { 16 | "$ref": "#/definitions/D", 17 | "description": "This one should be of type D and not object" 18 | } 19 | } 20 | }, 21 | "C": { 22 | "type": "string", 23 | "description": "Possible types", 24 | "enum": [ 25 | "First", 26 | "Second" 27 | ] 28 | }, 29 | "D": { 30 | "type": "object", 31 | "description": "Possible types" 32 | } 33 | }, 34 | "type": "object", 35 | "required": [ 36 | "signalPaths" 37 | ], 38 | "description": "This is the class E", 39 | "properties": { 40 | "type": { 41 | "$ref": "#/definitions/C", 42 | "description": "This is the type of E" 43 | }, 44 | "signalPaths": { 45 | "children": "array", 46 | "items": { 47 | "$ref": "#/definitions/B", 48 | "description": "This is a list of children" 49 | } 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/F.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "name": { 5 | "$ref": "./G.json", 6 | "description": "This is the type of G" 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/References/G.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "string", 3 | "nullable": true 4 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_array_property_has_maxitems_then_maxlength_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Array10 : System.Collections.ObjectModel.Collection 12 | { 13 | 14 | } 15 | 16 | public partial class Message 17 | { 18 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 19 | [System.ComponentModel.DataAnnotations.Required] 20 | [System.ComponentModel.DataAnnotations.MaxLength(10)] 21 | public Array10 Value { get; set; } = new Array10(); 22 | 23 | 24 | 25 | private System.Collections.Generic.IDictionary _additionalProperties; 26 | 27 | [Newtonsoft.Json.JsonExtensionData] 28 | public System.Collections.Generic.IDictionary AdditionalProperties 29 | { 30 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 31 | set { _additionalProperties = value; } 32 | } 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_array_property_has_minitems_then_minlength_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Required] 15 | [System.ComponentModel.DataAnnotations.MinLength(10)] 16 | public System.Collections.Generic.ICollection Value { get; set; } = new System.Collections.ObjectModel.Collection(); 17 | 18 | 19 | 20 | private System.Collections.Generic.IDictionary _additionalProperties; 21 | 22 | [Newtonsoft.Json.JsonExtensionData] 23 | public System.Collections.Generic.IDictionary AdditionalProperties 24 | { 25 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 26 | set { _additionalProperties = value; } 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_int32_property_has_minimum_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(10, int.MaxValue)] 15 | public int Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_int64_property_has_minimum_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(10L, long.MaxValue)] 15 | public long Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_int_property_has_maximum_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(int.MinValue, 20)] 15 | public int Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_integer_property_has_minimum_and_maximum_that_are_int64_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(-10000000000L, 10000000000L)] 15 | public long Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_integer_property_has_minimum_and_maximum_that_are_too_large_or_small_for_int64.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(-9223372036854775808L, 9223372036854775807L)] 15 | public long Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_integer_property_has_minimum_and_maximum_with_exclusive_true_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(-99999999, 99999999)] 15 | public int Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_number_property_has_minimum_and_maximum_that_are_decimal_then_range_attribute_is_rendered.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(typeof(decimal), "-100.50", "100.50")] 15 | public decimal Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_number_property_has_minimum_and_maximum_that_are_double_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(-10000000000D, 10000000000D)] 15 | public double Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_number_property_has_minimum_and_maximum_with_exclusive_true_and_multipleof_then_range_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Range(-100000000.4999D, 100000000.4999D)] 15 | public double Value { get; set; } 16 | 17 | 18 | 19 | private System.Collections.Generic.IDictionary _additionalProperties; 20 | 21 | [Newtonsoft.Json.JsonExtensionData] 22 | public System.Collections.Generic.IDictionary AdditionalProperties 23 | { 24 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 25 | set { _additionalProperties = value; } 26 | } 27 | 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_string_property_has_maxlength_then_stringlength_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] 15 | [System.ComponentModel.DataAnnotations.StringLength(50)] 16 | public string Value { get; set; } 17 | 18 | 19 | 20 | private System.Collections.Generic.IDictionary _additionalProperties; 21 | 22 | [Newtonsoft.Json.JsonExtensionData] 23 | public System.Collections.Generic.IDictionary AdditionalProperties 24 | { 25 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 26 | set { _additionalProperties = value; } 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_string_property_has_minlength_then_stringlength_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] 15 | [System.ComponentModel.DataAnnotations.StringLength(int.MaxValue, MinimumLength = 40)] 16 | public string Value { get; set; } 17 | 18 | 19 | 20 | private System.Collections.Generic.IDictionary _additionalProperties; 21 | 22 | [Newtonsoft.Json.JsonExtensionData] 23 | public System.Collections.Generic.IDictionary AdditionalProperties 24 | { 25 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 26 | set { _additionalProperties = value; } 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValidationAttributesTests.When_string_property_has_pattern_then_regularexpression_attribute_is_rendered_in_Swagger_mode.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class Message 12 | { 13 | [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Always)] 14 | [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] 15 | [System.ComponentModel.DataAnnotations.RegularExpression(@"[a-zA-Z0-9]{5,56}")] 16 | public string Value { get; set; } 17 | 18 | 19 | 20 | private System.Collections.Generic.IDictionary _additionalProperties; 21 | 22 | [Newtonsoft.Json.JsonExtensionData] 23 | public System.Collections.Generic.IDictionary AdditionalProperties 24 | { 25 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 26 | set { _additionalProperties = value; } 27 | } 28 | 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValueGeneratorTests.When_property_is_string_and_format_is_date_time_then_assign_default_value.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class MyClass 12 | { 13 | [Newtonsoft.Json.JsonProperty("dateTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 14 | public System.DateTime? DateTime { get; set; } = System.DateTime.Parse("31.12.9999 23:59:59"); 15 | 16 | 17 | 18 | private System.Collections.Generic.IDictionary _additionalProperties; 19 | 20 | [Newtonsoft.Json.JsonExtensionData] 21 | public System.Collections.Generic.IDictionary AdditionalProperties 22 | { 23 | get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary()); } 24 | set { _additionalProperties = value; } 25 | } 26 | 27 | } 28 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp.Tests/Snapshots/ValueGeneratorTests.When_schema_contains_range_then_code_is_correctly_generated.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | namespace MyNamespace 8 | { 9 | #pragma warning disable // Disable all warnings 10 | 11 | public partial class MyClass 12 | { 13 | [Newtonsoft.Json.JsonProperty("Foo", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] 14 | [System.ComponentModel.DataAnnotations.Range(2, int.MaxValue)] 15 | public int? Foo { get; set; } 16 | 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/CSharpClassStyle.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using System.ComponentModel; 10 | 11 | namespace NJsonSchema.CodeGeneration.CSharp 12 | { 13 | /// The CSharp styles. 14 | public enum CSharpClassStyle 15 | { 16 | /// Generates POCOs (Plain Old C# Objects). 17 | Poco, 18 | 19 | /// Generates classes implementing the interface. 20 | Inpc, 21 | 22 | /// Generates classes implementing the Prism base class. 23 | Prism, 24 | 25 | /// Generates Records - read only POCOs (Plain Old C# Objects). 26 | Record 27 | } 28 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonLibrary.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.CSharp 10 | { 11 | /// The CSharp JSON library to use. 12 | public enum CSharpJsonLibrary 13 | { 14 | /// Use Newtonsoft.Json 15 | NewtonsoftJson, 16 | 17 | /// Use System.Text.Json 18 | SystemTextJson 19 | } 20 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonPolymorphicSerializationStyle.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.CSharp 2 | { 3 | /// The CSharp JSON polymorphic serialization style. 4 | public enum CSharpJsonPolymorphicSerializationStyle 5 | { 6 | /// Use NJsonSchema polymorphic serialization 7 | NJsonSchema, 8 | 9 | /// Use System.Text.Json polymorphic serialization 10 | SystemTextJson 11 | } 12 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Models/DateFormatConverterTemplateModel.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using System.Linq; 10 | 11 | namespace NJsonSchema.CodeGeneration.CSharp.Models 12 | { 13 | /// The DateFormatConverterTemplateModel. 14 | public class DateFormatConverterTemplateModel 15 | { 16 | private readonly CSharpGeneratorSettings _settings; 17 | 18 | /// The DateFormatConverterTemplateModel. 19 | public DateFormatConverterTemplateModel(CSharpGeneratorSettings settings) 20 | { 21 | _settings = settings; 22 | } 23 | 24 | /// Gets or sets a value indicating whether to generate the DateFormatConverter class. 25 | public bool GenerateDateFormatConverterClass => _settings.ExcludedTypeNames?.Contains("DateFormatConverter") != true; 26 | 27 | /// Gets a value indicating whether to use System.Text.Json 28 | public bool UseSystemTextJson => _settings.JsonLibrary == CSharpJsonLibrary.SystemTextJson; 29 | 30 | /// Gets the date .NET type. 31 | public string DateType => _settings.DateType; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Models/FileTemplateModel.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.CSharp.Models 10 | { 11 | /// The CSharp file template model. 12 | public class FileTemplateModel 13 | { 14 | /// Gets or sets the namespace. 15 | public required string Namespace { get; set; } 16 | 17 | /// Gets or sets a value indicating whether the C#8 nullable reference types are enabled for this file. 18 | public bool GenerateNullableReferenceTypes { get; set; } 19 | 20 | /// Gets or sets the types code. 21 | public required string TypesCode { get; set; } 22 | } 23 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Models/JsonInheritanceConverterTemplateModel.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.CSharp.Models 10 | { 11 | /// The JsonInheritanceConverterTemplateModel. 12 | public class JsonInheritanceConverterTemplateModel 13 | { 14 | private readonly CSharpGeneratorSettings _settings; 15 | 16 | /// The DateFormatConverterTemplateModel. 17 | public JsonInheritanceConverterTemplateModel(CSharpGeneratorSettings settings) 18 | { 19 | _settings = settings; 20 | } 21 | 22 | /// Gets a value indicating whether to use System.Text.Json 23 | public bool UseSystemTextJson => _settings.JsonLibrary == CSharpJsonLibrary.SystemTextJson; 24 | 25 | /// Gets a value indicating whether to use System.Text.Json polymorphic serialization 26 | public bool UseSystemTextJsonPolymorphicSerialization => _settings.JsonPolymorphicSerializationStyle == CSharpJsonPolymorphicSerializationStyle.SystemTextJson; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0;net462;net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $author$ 7 | $description$ 8 | json schema validation generator codegen .net 9 | http://NJsonSchema.org 10 | https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.CodeGeneration.CSharp/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Annotations.liquid: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Body.liquid: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.Record.liquid: -------------------------------------------------------------------------------- 1 | {%- assign skipComma = true %} 2 | {% if HasInheritance %} 3 | {%- assign parentProperties = BaseClass.AllProperties %} 4 | {% else %} 5 | {%- assign parentProperties = "" | empty %} 6 | {% endif %} 7 | 8 | {%- assign sortedProperties = AllProperties | sort: "Name" %} 9 | {%- assign sortedParentProperties = parentProperties | sort: "Name" %} 10 | 11 | {%- if UseSystemTextJson %} 12 | [System.Text.Json.Serialization.JsonConstructor] 13 | {%- else %} 14 | [Newtonsoft.Json.JsonConstructor] 15 | {%- endif %} 16 | {% if IsAbstract %}protected{% else %}public{% endif %} {{ClassName}}({% for property in sortedProperties %}{%- if skipComma %}{%- assign skipComma = false %}{% else %}, {% endif %}{{ property.Type }} @{{ property.PropertyName | lowercamelcase }}{% endfor %}) 17 | {%- assign skipComma = true %} 18 | {%- if HasInheritance %} 19 | : base({%- for property in sortedParentProperties %}{%- if skipComma %}{%- assign skipComma = false %}{% else %}, {% endif %}{{ property.PropertyName | lowercamelcase }}{%- endfor %}) 20 | {%- endif %} 21 | { 22 | {%- for property in Properties %} 23 | this.{{property.PropertyName}} = @{{property.PropertyName | lowercamelcase}}; 24 | {%- endfor %} 25 | } 26 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.liquid: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Constructor.liquid -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.FromJson.liquid: -------------------------------------------------------------------------------- 1 | public static {{ ClassName }} FromJson(string data) 2 | { 3 | {%- if UseSystemTextJson %} 4 | var options = {{ JsonSerializerParameterCode }}; 5 | {%- if JsonConvertersArrayCode contains "System.Text.Json.Serialization.JsonConverter[]" %} 6 | var converters = {{ JsonConvertersArrayCode }}; 7 | foreach(var converter in converters) 8 | options.Converters.Add(converter); 9 | {%- endif %} 10 | return System.Text.Json.JsonSerializer.Deserialize<{{ ClassName }}>(data, options); 11 | {%- else %} 12 | return Newtonsoft.Json.JsonConvert.DeserializeObject<{{ ClassName }}>(data, {{ JsonSerializerParameterCode }}); 13 | {%- endif %} 14 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Inheritance.liquid: -------------------------------------------------------------------------------- 1 | {%- if RenderInpc %} 2 | {% if HasInheritance %} : {{ BaseClassName }}{% else %} : System.ComponentModel.INotifyPropertyChanged{% endif %} 3 | {%- elsif RenderPrism %} 4 | {% if HasInheritance %} : {{ BaseClassName }}{% else %} : Prism.Mvvm.BindableBase{% endif %} 5 | {%- else %} 6 | {% if HasInheritance %} : {{ BaseClassName }}{% endif %} 7 | {%- endif %} -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Inpc.liquid: -------------------------------------------------------------------------------- 1 | {% if HasInheritance == false -%} 2 | public event System.ComponentModel.PropertyChangedEventHandler{% if GenerateNullableReferenceTypes %}?{% endif %} PropertyChanged; 3 | 4 | protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string{% if GenerateNullableReferenceTypes %}?{% endif %} propertyName = null) 5 | { 6 | var handler = PropertyChanged; 7 | if (handler != null) 8 | handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); 9 | } 10 | {% endif -%} 11 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.Property.Annotations.liquid: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Class.ToJson.liquid: -------------------------------------------------------------------------------- 1 | public string ToJson() 2 | { 3 | {%- if UseSystemTextJson %} 4 | var options = {{ JsonSerializerParameterCode }}; 5 | {%- if JsonConvertersArrayCode contains "System.Text.Json.Serialization.JsonConverter[]" %} 6 | var converters = {{ JsonConvertersArrayCode }}; 7 | foreach(var converter in converters) 8 | options.Converters.Add(converter); 9 | {%- endif %} 10 | return System.Text.Json.JsonSerializer.Serialize(this, options); 11 | {%- else %} 12 | return Newtonsoft.Json.JsonConvert.SerializeObject(this, {{ JsonSerializerParameterCode }}); 13 | {%- endif %} 14 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/DateFormatConverter.liquid: -------------------------------------------------------------------------------- 1 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "{{ ToolchainVersion }}")] 2 | {%- if UseSystemTextJson -%} 3 | internal class DateFormatConverter : System.Text.Json.Serialization.JsonConverter<{{ DateType }}> 4 | { 5 | public override {{ DateType }} Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) 6 | { 7 | var dateTime = reader.GetString(); 8 | if (dateTime == null) 9 | { 10 | throw new System.Text.Json.JsonException("Unexpected JsonTokenType.Null"); 11 | } 12 | 13 | return {{ DateType }}.Parse(dateTime); 14 | } 15 | 16 | public override void Write(System.Text.Json.Utf8JsonWriter writer, {{ DateType }} value, System.Text.Json.JsonSerializerOptions options) 17 | { 18 | writer.WriteStringValue(value.ToString("yyyy-MM-dd")); 19 | } 20 | } 21 | {%- else -%} 22 | internal class DateFormatConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter 23 | { 24 | public DateFormatConverter() 25 | { 26 | DateTimeFormat = "yyyy-MM-dd"; 27 | } 28 | } 29 | {%- endif %} -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Annotations.liquid: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Member.Annotations.liquid: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.liquid: -------------------------------------------------------------------------------- 1 | {%- if HasDescription -%} 2 | /// 3 | /// {{ Description | csharpdocs }} 4 | /// 5 | {%- endif -%} 6 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "{{ ToolchainVersion }}")] 7 | {%- if IsEnumAsBitFlags -%} 8 | [System.Flags] 9 | {%- endif -%} 10 | {%- template Enum.Annotations -%} 11 | {{ TypeAccessModifier }} enum {{ Name }}{%- if HasExtendedValueRange %} : long{% endif %} 12 | { 13 | {%- for enum in Enums %} 14 | {%- if IsStringEnum -%} 15 | [System.Runtime.Serialization.EnumMember(Value = @"{{ enum.Value | replace: '"', '""' }}")] 16 | {%- endif -%} 17 | {%- template Enum.Member.Annotations -%} 18 | {%- if IsEnumAsBitFlags -%} 19 | {{ enum.Name }} = {{ enum.InternalFlagValue }}, 20 | {%- else -%} 21 | {{ enum.Name }} = {{ enum.InternalValue }}, 22 | {%- endif -%} 23 | 24 | {%- endfor %} 25 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/File.liquid: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // Generated using the NJsonSchema v{{ ToolchainVersion }} (http://NJsonSchema.org) 4 | // 5 | //---------------------- 6 | 7 | {%- if GenerateNullableReferenceTypes %} 8 | #nullable enable 9 | 10 | {%- endif %} 11 | namespace {{ Namespace }} 12 | { 13 | #pragma warning disable // Disable all warnings 14 | 15 | {{ TypesCode | tab }} 16 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.CSharp/Templates/JsonInheritanceAttribute.liquid: -------------------------------------------------------------------------------- 1 | {%- if UseSystemTextJsonPolymorphicSerialization == false -%} 2 | [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "{{ ToolchainVersion }}")] 3 | [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface, AllowMultiple = true)] 4 | internal class JsonInheritanceAttribute : System.Attribute 5 | { 6 | public JsonInheritanceAttribute(string key, System.Type type) 7 | { 8 | Key = key; 9 | Type = type; 10 | } 11 | 12 | public string Key { get; } 13 | 14 | public System.Type Type { get; } 15 | } 16 | {%- endif -%} -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.Tests/ApiSurfaceGuard.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.Tests; 2 | 3 | public class ApiSurfaceGuard 4 | { 5 | private abstract class TypeResolverBaseApiGuard : TypeResolverBase 6 | { 7 | protected TypeResolverBaseApiGuard(CodeGeneratorSettingsBase settings) : base(settings) 8 | { 9 | } 10 | 11 | // dummy implementation making sure this method stays overridable 12 | public override string GetOrGenerateTypeName(JsonSchema schema, string typeNameHint) 13 | { 14 | throw new System.NotImplementedException(); 15 | } 16 | 17 | // dummy implementation making sure this method stays overridable 18 | public override JsonSchema RemoveNullability(JsonSchema schema) 19 | { 20 | throw new System.NotImplementedException(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | $(TargetFrameworks);net472 6 | false 7 | $(NoWarn),1998,1591,618,IDE1006 8 | disable 9 | false 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.Tests/TemplateFactoryTests.cs: -------------------------------------------------------------------------------- 1 | using Fluid; 2 | using NJsonSchema.CodeGeneration.CSharp; 3 | 4 | namespace NJsonSchema.CodeGeneration.Tests; 5 | 6 | public class TemplateFactoryTests 7 | { 8 | [Fact] 9 | public void Can_customize_liquid_parser() 10 | { 11 | var generatorSettings = new CSharpGeneratorSettings 12 | { 13 | TemplateDirectory = "Templates", 14 | }; 15 | 16 | var factory = new DefaultTemplateFactory(generatorSettings, [typeof(CSharpGeneratorSettings).Assembly]) 17 | { 18 | FluidParser = new LiquidParser(new FluidParserOptions { AllowLiquidTag = true }), 19 | }; 20 | generatorSettings.TemplateFactory = factory; 21 | 22 | var template = factory.CreateTemplate("csharp", "inline-liquid", new { }); 23 | 24 | var templateResult = template.Render(); 25 | 26 | Assert.Equal("WELCOME TO THE LIQUID TAG", templateResult); 27 | } 28 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.Tests/Templates/elseif.liquid: -------------------------------------------------------------------------------- 1 | {% if false %} 2 | Wrong 3 | {% elseif true %} 4 | Hello 5 | {% endif %} 6 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.Tests/Templates/inline-liquid.liquid: -------------------------------------------------------------------------------- 1 | {% 2 | liquid 3 | echo 4 | 'welcome ' | upcase 5 | echo 'to the liquid tag' 6 | | upcase 7 | %} -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.Tests/VerifyHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NJsonSchema.CodeGeneration.Tests; 4 | 5 | public static class VerifyHelper 6 | { 7 | /// 8 | /// Helper to run verify tests with sane defaults. 9 | /// 10 | public static SettingsTask Verify(string output, [CallerFilePath] string sourceFile = "") 11 | { 12 | return Verifier 13 | .Verify(output, sourceFile: sourceFile) 14 | .ScrubLinesContaining( 15 | StringComparison.OrdinalIgnoreCase, 16 | "Generated using the NSwag toolchain", 17 | "Generated using the NJsonSchema", 18 | "[System.CodeDom.Compiler.GeneratedCode(\"NJsonSchema\"") 19 | .UseDirectory("Snapshots"); 20 | } 21 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/ClassOrderTests.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests 2 | { 3 | public class ClassOrderTests 4 | { 5 | [Fact] 6 | public void When_class_order_is_wrong_then_classes_are_correctly_reordered() 7 | { 8 | // Arrange 9 | var classes = new List 10 | { 11 | new CodeArtifact("Car", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Undefined, ""), 12 | new CodeArtifact("Apple", "List", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Undefined, ""), 13 | new CodeArtifact("Professor", "Teacher", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Undefined, ""), 14 | new CodeArtifact("Teacher", "Person[]", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Undefined, ""), 15 | new CodeArtifact("Fruit", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Undefined, ""), 16 | new CodeArtifact("Person", CodeArtifactType.Class, CodeArtifactLanguage.CSharp, CodeArtifactCategory.Undefined, "") 17 | }; 18 | 19 | // Act 20 | classes = classes.OrderByBaseDependency().ToList(); 21 | var order = string.Join(", ", classes.Select(c => c.TypeName)); 22 | 23 | // Assert 24 | Assert.Equal("Car, Fruit, Apple, Person, Teacher, Professor", order); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Models/Address.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests.Models 2 | { 3 | public class Address 4 | { 5 | public string Street { get; set; } 6 | 7 | public string City { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Models/File.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests.Models 2 | { 3 | public class File 4 | { 5 | public byte[] Content { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Models/Gender.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests.Models 2 | { 3 | public enum Gender 4 | { 5 | Male, 6 | Female 7 | } 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Models/Person.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.ComponentModel.DataAnnotations; 3 | using Newtonsoft.Json; 4 | using NJsonSchema.Annotations; 5 | 6 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests.Models 7 | { 8 | public class Person 9 | { 10 | [Required] 11 | public string FirstName { get; set; } 12 | 13 | [JsonProperty("lastName")] 14 | public string LastName { get; set; } 15 | 16 | [ReadOnly(true)] 17 | public DateTime Birthday { get; set; } 18 | 19 | public TimeSpan TimeSpan { get; set; } 20 | 21 | public TimeSpan? TimeSpanOrNull { get; set; } 22 | 23 | public Gender Gender { get; set; } 24 | 25 | public Gender? GenderOrNull { get; set; } 26 | 27 | [JsonProperty("address", Required = Required.Always)] 28 | public Address Address { get; set; } 29 | 30 | [CanBeNull] 31 | public Address AddressOrNull { get; set; } 32 | 33 | public List Array { get; set; } 34 | 35 | public Dictionary Dictionary { get; set; } 36 | } 37 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Models/Teacher.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests.Models 2 | { 3 | public class Teacher : Person 4 | { 5 | public string Class { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/NJsonSchema.CodeGeneration.TypeScript.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | $(TargetFrameworks);net472 6 | false 7 | disable 8 | latest-Minimal 9 | $(NoWarn);1591 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/NJsonSchema.CodeGeneration.TypeScript.Tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | NJsonSchema.CodeGeneration.TypeScript.Tests 5 | 6 | 7 | 8 | 9 | Foobar. 10 | 11 | 12 | 13 | 14 | Foobar. 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/PropertyNameTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.CodeGeneration.Tests; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | 4 | namespace NJsonSchema.CodeGeneration.TypeScript.Tests; 5 | 6 | public class PropertyNameTests 7 | { 8 | private class TypeWithRestrictedProperties 9 | { 10 | public string Constructor { get; set; } 11 | public string Init { get; set; } 12 | public string FromJS { get; set; } 13 | public string ToJSON { get; set; } 14 | } 15 | 16 | [Fact] 17 | public async Task When_class_has_restricted_properties_they_are_escaped() 18 | { 19 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 20 | 21 | var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeScriptVersion = 4.3m }); 22 | var output = generator.GenerateFile(nameof(TypeWithRestrictedProperties)); 23 | 24 | await VerifyHelper.Verify(output); 25 | 26 | CodeCompiler.AssertCompile(output); 27 | } 28 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ClassGenerationTests.Verify_output_style=Interface_version=1.8.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Person { 13 | FirstName: string; 14 | LastName: string; 15 | } 16 | 17 | export interface Student extends Person { 18 | Study: string; 19 | } 20 | 21 | export interface MyClass { 22 | Name: string; 23 | DateOfBirth: Date; 24 | PrimitiveArray: number[]; 25 | PrimitiveDictionary: { [key: string]: number; }; 26 | DateArray: Date[]; 27 | DateDictionary: { [key: string]: Date; }; 28 | Reference: Student; 29 | Array: Student[]; 30 | Dictionary: { [key: string]: Student; }; 31 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ClassGenerationTests.Verify_output_style=Interface_version=2.1.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Person { 13 | FirstName: string | undefined; 14 | LastName: string | undefined; 15 | } 16 | 17 | export interface Student extends Person { 18 | Study: string | undefined; 19 | } 20 | 21 | export interface MyClass { 22 | Name: string | undefined; 23 | DateOfBirth: Date; 24 | PrimitiveArray: number[] | undefined; 25 | PrimitiveDictionary: { [key: string]: number; } | undefined; 26 | DateArray: Date[] | undefined; 27 | DateDictionary: { [key: string]: Date; } | undefined; 28 | Reference: Student | undefined; 29 | Array: Student[] | undefined; 30 | Dictionary: { [key: string]: Student; } | undefined; 31 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ClassGenerationTests.Verify_output_style=Interface_version=2.7.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Person { 13 | FirstName: string | undefined; 14 | LastName: string | undefined; 15 | } 16 | 17 | export interface Student extends Person { 18 | Study: string | undefined; 19 | } 20 | 21 | export interface MyClass { 22 | Name: string | undefined; 23 | DateOfBirth: Date; 24 | PrimitiveArray: number[] | undefined; 25 | PrimitiveDictionary: { [key: string]: number; } | undefined; 26 | DateArray: Date[] | undefined; 27 | DateDictionary: { [key: string]: Date; } | undefined; 28 | Reference: Student | undefined; 29 | Array: Student[] | undefined; 30 | Dictionary: { [key: string]: Student; } | undefined; 31 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/ClassGenerationTests.Verify_output_style=Interface_version=4.3.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Person { 13 | FirstName: string | undefined; 14 | LastName: string | undefined; 15 | } 16 | 17 | export interface Student extends Person { 18 | Study: string | undefined; 19 | } 20 | 21 | export interface MyClass { 22 | Name: string | undefined; 23 | DateOfBirth: Date; 24 | PrimitiveArray: number[] | undefined; 25 | PrimitiveDictionary: { [key: string]: number; } | undefined; 26 | DateArray: Date[] | undefined; 27 | DateDictionary: { [key: string]: Date; } | undefined; 28 | Reference: Student | undefined; 29 | Array: Student[] | undefined; 30 | Dictionary: { [key: string]: Student; } | undefined; 31 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/TypeScriptDiscriminatorTests.When_generating_interface_contract_add_discriminator.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Base { 13 | Type: EBase; 14 | } 15 | 16 | export enum EBase { 17 | OneChild = "OneChild", 18 | SecondChild = "SecondChild", 19 | } 20 | 21 | export interface OneChild extends Base { 22 | A: string; 23 | Type: EBase.OneChild; 24 | } 25 | 26 | export interface SecondChild extends Base { 27 | B: string; 28 | Type: EBase.SecondChild; 29 | } 30 | 31 | export interface MyClass { 32 | Child: Base; 33 | Children: Base[]; 34 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/TypeScriptDiscriminatorTests.When_generating_interface_contract_add_discriminator_string_literal.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Base { 13 | Type: EBase; 14 | } 15 | 16 | export type EBase = "OneChild" | "SecondChild"; 17 | 18 | export interface OneChild extends Base { 19 | A: string; 20 | Type: 'OneChild'; 21 | } 22 | 23 | export interface SecondChild extends Base { 24 | B: string; 25 | Type: 'SecondChild'; 26 | } 27 | 28 | export interface MyClass { 29 | Child: Base; 30 | Children: Base[]; 31 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/Snapshots/TypeScriptDiscriminatorTests.When_parameter_is_abstract_then_generate_union_interface.verified.txt: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // 4 | //---------------------- 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | export interface Base { 13 | Type: string; 14 | } 15 | 16 | export interface OneChild extends Base { 17 | A: string; 18 | Type: EBase.OneChild; 19 | } 20 | 21 | export enum EBase { 22 | OneChild = "OneChild", 23 | SecondChild = "SecondChild", 24 | } 25 | 26 | export interface SecondChild extends Base { 27 | B: string; 28 | Type: EBase.SecondChild; 29 | } 30 | 31 | export interface MyClass { 32 | Child: OneChild | SecondChild; 33 | Children: (OneChild | SecondChild)[]; 34 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "NJsonSchema.CodeGeneration.TypeScript.Tests", 3 | "lockfileVersion": 3, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "devDependencies": { 8 | "typescript": "^5.8.3" 9 | } 10 | }, 11 | "node_modules/typescript": { 12 | "version": "5.8.3", 13 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", 14 | "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", 15 | "dev": true, 16 | "license": "Apache-2.0", 17 | "bin": { 18 | "tsc": "bin/tsc", 19 | "tsserver": "bin/tsserver" 20 | }, 21 | "engines": { 22 | "node": ">=14.17" 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript.Tests/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "typescript": "^5.8.3" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0;net462;net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $author$ 7 | $description$ 8 | json schema validation generator codegen .net 9 | http://NJsonSchema.org 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.CodeGeneration.TypeScript/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/Templates/Enum.StringLiteral.liquid: -------------------------------------------------------------------------------- 1 | {%- if HasDescription -%} 2 | /** {{ Description }} */ 3 | {%- endif -%} 4 | {%- if ExportTypes %}export {% endif %}type {{ Name }} = {% for enumeration in Enums %}{%- if Enums.first.Value != enumeration.Value %} | {% endif %}{{ enumeration.Value }}{% endfor %}; -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/Templates/Enum.liquid: -------------------------------------------------------------------------------- 1 | {%- if HasDescription -%} 2 | /** {{ Description }} */ 3 | {%- endif -%} 4 | {% if ExportTypes %}export {% endif %}enum {{ Name }} { 5 | {%- for enumeration in Enums -%} 6 | {{ enumeration.Name }} = {{ enumeration.Value }}, 7 | {%- endfor -%} 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/Templates/File.FormatDate.liquid: -------------------------------------------------------------------------------- 1 | function formatDate(d: Date) { 2 | return d.getFullYear() + '-' + 3 | (d.getMonth() < 9 ? ('0' + (d.getMonth()+1)) : (d.getMonth()+1)) + '-' + 4 | (d.getDate() < 10 ? ('0' + d.getDate()) : d.getDate()); 5 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/Templates/File.ParseDateOnly.liquid: -------------------------------------------------------------------------------- 1 | function parseDateOnly(s: string) { 2 | const date = new Date(s); 3 | return new Date(date.getTime() + 4 | date.getTimezoneOffset() * 60000); 5 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/Templates/File.liquid: -------------------------------------------------------------------------------- 1 | //---------------------- 2 | // 3 | // Generated using the NSwag toolchain v{{ ToolchainVersion }} (http://NJsonSchema.org) 4 | // 5 | //---------------------- 6 | 7 | {{ ExtensionCode.ImportCode }} 8 | 9 | {%- if HasModuleName %} 10 | module {{ ModuleName }} { 11 | {%- endif %} 12 | {%- if HasNamespace %} 13 | namespace {{ Namespace }} { 14 | {%- endif %} 15 | {{ ExtensionCode.TopCode }} 16 | 17 | {{ Types }} 18 | 19 | {{ ExtensionCode.BottomCode }} 20 | 21 | {%- if HasNamespace %} 22 | } 23 | {%- endif %} 24 | {%- if HasModuleName %} 25 | } 26 | {%- endif %} -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/Templates/Interface.liquid: -------------------------------------------------------------------------------- 1 | {%- if HasDescription -%} 2 | /** {{ Description }} */ 3 | {%- endif -%} 4 | {% if ExportTypes %}export {% endif %}interface {{ ClassName }}{{ Inheritance }} { 5 | {%- for property in Properties -%} 6 | {%- if property.HasDescription -%} 7 | /** {{ property.Description }} */ 8 | {%- endif -%} 9 | {% if property.IsReadOnly %}readonly {% endif %}{{ property.InterfaceName }}{% if property.IsOptional %}?{% endif %}: {{ property.Type }}{{ property.TypePostfix }}; 10 | {%- endfor -%} 11 | {%- if HasIndexerProperty -%} 12 | 13 | [key: string]: {{ IndexerPropertyValueType }}; 14 | {%- endif -%} 15 | } 16 | {%- if GenerateTypeCheckFunctions and HasInheritance -%} 17 | 18 | {% if ExportTypes %}export {% endif %}function is{{ ClassName }}(object: any): object is {{ ClassName }} { 19 | return object && object['{{ BaseDiscriminator }}'] === '{{ DiscriminatorName }}'; 20 | } 21 | {%- endif -%} -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptDateTimeType.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.TypeScript 10 | { 11 | /// Specifies the TypeScript date time type handling. 12 | public enum TypeScriptDateTimeType 13 | { 14 | /// Uses the JavaScript Date object for date time handling. 15 | Date, 16 | 17 | /// Uses the Moment.js for date time handling. 18 | MomentJS, 19 | 20 | /// Uses the strings for date time handling (no conversion). 21 | String, 22 | 23 | /// Uses the Moment.js for date time with offset handling. 24 | OffsetMomentJS, 25 | 26 | /// Uses Luxon for date time handling. 27 | Luxon, 28 | 29 | /// Uses the DayJS.js for date time handling. 30 | DayJS, 31 | } 32 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptEnumStyle.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | //----------------------------------------------------------------------- 7 | 8 | namespace NJsonSchema.CodeGeneration.TypeScript 9 | { 10 | /// The TypeScript enum styles. 11 | public enum TypeScriptEnumStyle 12 | { 13 | /// Generates enum. 14 | Enum, 15 | 16 | /// Generates enum as a string literal. 17 | StringLiteral, 18 | } 19 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptNullValue.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.TypeScript 10 | { 11 | /// The TypeScript null value used in object initializers. 12 | public enum TypeScriptNullValue 13 | { 14 | /// JavaScript null. 15 | Null, 16 | 17 | /// JavaScript undefined. 18 | Undefined 19 | } 20 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeStyle.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.TypeScript 10 | { 11 | /// The TypeScript type styles. 12 | public enum TypeScriptTypeStyle 13 | { 14 | /// Generates interfaces which can add typings to existing JSON. 15 | Interface, 16 | 17 | /// Generates classes which can be constructed from JSON. 18 | Class, 19 | 20 | /// Generates classes with KnockoutJS observable properties. 21 | KnockoutClass 22 | } 23 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/CodeArtifactCategory.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// The code artifact category. 12 | public enum CodeArtifactCategory 13 | { 14 | /// Undefined. 15 | Undefined, 16 | 17 | /// Client. 18 | Client, 19 | 20 | /// Contract. 21 | Contract, 22 | 23 | /// Utility. 24 | Utility 25 | } 26 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/CodeArtifactLanguage.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// The code artifact type. 12 | public enum CodeArtifactLanguage 13 | { 14 | /// Undefined. 15 | Undefined, 16 | 17 | /// C#. 18 | CSharp, 19 | 20 | /// TypeScript. 21 | TypeScript, 22 | 23 | /// Html. 24 | Html 25 | } 26 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/CodeArtifactType.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// The code artifact type. 12 | public enum CodeArtifactType 13 | { 14 | /// Undefined. 15 | Undefined, 16 | 17 | /// A class (e.g. C# or TypeScript class). 18 | Class, 19 | 20 | /// An interface (e.g. C# or TypeScript interface). 21 | Interface, 22 | 23 | /// An enum (e.g. C# or TypeScript interface). 24 | Enum, 25 | 26 | /// An internal function. 27 | Function 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/IEnumNameGenerator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// Generates the name of an enumeration entry. 12 | public interface IEnumNameGenerator 13 | { 14 | /// Generates the enumeration name/key of the given enumeration entry. 15 | /// The index of the enumeration value (check and ). 16 | /// The name/key. 17 | /// The value. 18 | /// The schema. 19 | /// The enumeration name. 20 | string Generate(int index, string? name, object? value, JsonSchema schema); 21 | } 22 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/IPropertyNameGenerator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// Generates the property name for a given . 12 | public interface IPropertyNameGenerator 13 | { 14 | /// Generates the property name. 15 | /// The property. 16 | /// The new name. 17 | string Generate(JsonSchemaProperty property); 18 | } 19 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/ITemplate.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// Interface for a template. 12 | public interface ITemplate 13 | { 14 | /// Renders the template. 15 | /// The output. 16 | string Render(); 17 | } 18 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/ITemplateFactory.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration 10 | { 11 | /// The interface of a code generator template factory. 12 | public interface ITemplateFactory 13 | { 14 | /// Creates a template for the given language, template name and template model. 15 | /// The language (i.e. 'CSharp' or 'TypeScript'). 16 | /// The template name. 17 | /// The template model. 18 | /// The template. 19 | ITemplate CreateTemplate(string language, string template, object model); 20 | } 21 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/Models/EnumerationItemModel.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.CodeGeneration.Models 10 | { 11 | /// Describes an enumeration entry. 12 | public class EnumerationItemModel 13 | { 14 | /// Gets or sets the name. 15 | public required string Name { get; set; } 16 | 17 | /// Gets or sets the original name. 18 | public required string OriginalName { get; set; } 19 | 20 | /// Gets or sets the value. 21 | public required string Value { get; set; } 22 | 23 | /// Gets or sets the internal value (e.g. the underlying/system value). 24 | public string? InternalValue { get; set; } 25 | 26 | /// Gets or sets the internal flag value (e.g. the underlying/system value). 27 | public string? InternalFlagValue { get; set; } 28 | } 29 | } -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/NJsonSchema.CodeGeneration.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $author$ 7 | $description$ 8 | json schema validation generator codegen .net 9 | http://NJsonSchema.org 10 | https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/NJsonSchema.CodeGeneration/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.CodeGeneration/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema.Demo.Performance/NJsonSchema.Demo.Performance.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | false 7 | $(NoWarn);1591;CS8618 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/NJsonSchema.Demo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | false 6 | true 7 | 8 | Exe 9 | 10 | disable 11 | $(NoWarn);CS1591;IDE0005 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/default.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "invalid type for default", 4 | "schema": { 5 | "properties": { 6 | "foo": { 7 | "type": "integer", 8 | "default": [] 9 | } 10 | } 11 | }, 12 | "tests": [ 13 | { 14 | "description": "valid when property is specified", 15 | "data": {"foo": 13}, 16 | "valid": true 17 | }, 18 | { 19 | "description": "still valid when the invalid default is used", 20 | "data": {}, 21 | "valid": true 22 | } 23 | ] 24 | }, 25 | { 26 | "description": "invalid string value for default", 27 | "schema": { 28 | "properties": { 29 | "bar": { 30 | "type": "string", 31 | "minLength": 4, 32 | "default": "bad" 33 | } 34 | } 35 | }, 36 | "tests": [ 37 | { 38 | "description": "valid when property is specified", 39 | "data": {"bar": "good"}, 40 | "valid": true 41 | }, 42 | { 43 | "description": "still valid when the invalid default is used", 44 | "data": {}, 45 | "valid": true 46 | } 47 | ] 48 | } 49 | ] 50 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/definitions.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "valid definition", 4 | "schema": {"$ref": "http://json-schema.org/draft-04/schema#"}, 5 | "tests": [ 6 | { 7 | "description": "valid definition schema", 8 | "data": { 9 | "definitions": { 10 | "foo": {"type": "integer"} 11 | } 12 | }, 13 | "valid": true 14 | } 15 | ] 16 | }, 17 | { 18 | "description": "invalid definition", 19 | "schema": {"$ref": "http://json-schema.org/draft-04/schema#"}, 20 | "tests": [ 21 | { 22 | "description": "invalid definition schema", 23 | "data": { 24 | "definitions": { 25 | "foo": {"type": 1} 26 | } 27 | }, 28 | "valid": false 29 | } 30 | ] 31 | } 32 | ] 33 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/items.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "a schema given for items", 4 | "schema": { 5 | "items": {"type": "integer"} 6 | }, 7 | "tests": [ 8 | { 9 | "description": "valid items", 10 | "data": [ 1, 2, 3 ], 11 | "valid": true 12 | }, 13 | { 14 | "description": "wrong type of items", 15 | "data": [1, "x"], 16 | "valid": false 17 | }, 18 | { 19 | "description": "ignores non-arrays", 20 | "data": {"foo" : "bar"}, 21 | "valid": true 22 | } 23 | ] 24 | }, 25 | { 26 | "description": "an array of schemas for items", 27 | "schema": { 28 | "items": [ 29 | {"type": "integer"}, 30 | {"type": "string"} 31 | ] 32 | }, 33 | "tests": [ 34 | { 35 | "description": "correct types", 36 | "data": [ 1, "foo" ], 37 | "valid": true 38 | }, 39 | { 40 | "description": "wrong types", 41 | "data": [ "foo", 1 ], 42 | "valid": false 43 | } 44 | ] 45 | } 46 | ] 47 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/maxItems.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "maxItems validation", 4 | "schema": {"maxItems": 2}, 5 | "tests": [ 6 | { 7 | "description": "shorter is valid", 8 | "data": [1], 9 | "valid": true 10 | }, 11 | { 12 | "description": "exact length is valid", 13 | "data": [1, 2], 14 | "valid": true 15 | }, 16 | { 17 | "description": "too long is invalid", 18 | "data": [1, 2, 3], 19 | "valid": false 20 | }, 21 | { 22 | "description": "ignores non-arrays", 23 | "data": "foobar", 24 | "valid": true 25 | } 26 | ] 27 | } 28 | ] 29 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/maxLength.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "maxLength validation", 4 | "schema": {"maxLength": 2}, 5 | "tests": [ 6 | { 7 | "description": "shorter is valid", 8 | "data": "f", 9 | "valid": true 10 | }, 11 | { 12 | "description": "exact length is valid", 13 | "data": "fo", 14 | "valid": true 15 | }, 16 | { 17 | "description": "too long is invalid", 18 | "data": "foo", 19 | "valid": false 20 | }, 21 | { 22 | "description": "ignores non-strings", 23 | "data": 100, 24 | "valid": true 25 | }, 26 | { 27 | "description": "two supplementary Unicode code points is long enough", 28 | "data": "\uD83D\uDCA9\uD83D\uDCA9", 29 | "valid": true 30 | } 31 | ] 32 | } 33 | ] 34 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/maxProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "maxProperties validation", 4 | "schema": {"maxProperties": 2}, 5 | "tests": [ 6 | { 7 | "description": "shorter is valid", 8 | "data": {"foo": 1}, 9 | "valid": true 10 | }, 11 | { 12 | "description": "exact length is valid", 13 | "data": {"foo": 1, "bar": 2}, 14 | "valid": true 15 | }, 16 | { 17 | "description": "too long is invalid", 18 | "data": {"foo": 1, "bar": 2, "baz": 3}, 19 | "valid": false 20 | }, 21 | { 22 | "description": "ignores non-objects", 23 | "data": "foobar", 24 | "valid": true 25 | } 26 | ] 27 | } 28 | ] 29 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/maximum.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "maximum validation", 4 | "schema": {"maximum": 3.0}, 5 | "tests": [ 6 | { 7 | "description": "below the maximum is valid", 8 | "data": 2.6, 9 | "valid": true 10 | }, 11 | { 12 | "description": "above the maximum is invalid", 13 | "data": 3.5, 14 | "valid": false 15 | }, 16 | { 17 | "description": "ignores non-numbers", 18 | "data": "x", 19 | "valid": true 20 | } 21 | ] 22 | }, 23 | { 24 | "description": "exclusiveMaximum validation", 25 | "schema": { 26 | "maximum": 3.0, 27 | "exclusiveMaximum": true 28 | }, 29 | "tests": [ 30 | { 31 | "description": "below the maximum is still valid", 32 | "data": 2.2, 33 | "valid": true 34 | }, 35 | { 36 | "description": "boundary point is invalid", 37 | "data": 3.0, 38 | "valid": false 39 | } 40 | ] 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/minItems.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "minItems validation", 4 | "schema": {"minItems": 1}, 5 | "tests": [ 6 | { 7 | "description": "longer is valid", 8 | "data": [1, 2], 9 | "valid": true 10 | }, 11 | { 12 | "description": "exact length is valid", 13 | "data": [1], 14 | "valid": true 15 | }, 16 | { 17 | "description": "too short is invalid", 18 | "data": [], 19 | "valid": false 20 | }, 21 | { 22 | "description": "ignores non-arrays", 23 | "data": "", 24 | "valid": true 25 | } 26 | ] 27 | } 28 | ] 29 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/minLength.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "minLength validation", 4 | "schema": {"minLength": 2}, 5 | "tests": [ 6 | { 7 | "description": "longer is valid", 8 | "data": "foo", 9 | "valid": true 10 | }, 11 | { 12 | "description": "exact length is valid", 13 | "data": "fo", 14 | "valid": true 15 | }, 16 | { 17 | "description": "too short is invalid", 18 | "data": "f", 19 | "valid": false 20 | }, 21 | { 22 | "description": "ignores non-strings", 23 | "data": 1, 24 | "valid": true 25 | }, 26 | { 27 | "description": "one supplementary Unicode code point is not long enough", 28 | "data": "\uD83D\uDCA9", 29 | "valid": false 30 | } 31 | ] 32 | } 33 | ] 34 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/minProperties.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "minProperties validation", 4 | "schema": {"minProperties": 1}, 5 | "tests": [ 6 | { 7 | "description": "longer is valid", 8 | "data": {"foo": 1, "bar": 2}, 9 | "valid": true 10 | }, 11 | { 12 | "description": "exact length is valid", 13 | "data": {"foo": 1}, 14 | "valid": true 15 | }, 16 | { 17 | "description": "too short is invalid", 18 | "data": {}, 19 | "valid": false 20 | }, 21 | { 22 | "description": "ignores non-objects", 23 | "data": "", 24 | "valid": true 25 | } 26 | ] 27 | } 28 | ] 29 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/minimum.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "minimum validation", 4 | "schema": {"minimum": 1.1}, 5 | "tests": [ 6 | { 7 | "description": "above the minimum is valid", 8 | "data": 2.6, 9 | "valid": true 10 | }, 11 | { 12 | "description": "below the minimum is invalid", 13 | "data": 0.6, 14 | "valid": false 15 | }, 16 | { 17 | "description": "ignores non-numbers", 18 | "data": "x", 19 | "valid": true 20 | } 21 | ] 22 | }, 23 | { 24 | "description": "exclusiveMinimum validation", 25 | "schema": { 26 | "minimum": 1.1, 27 | "exclusiveMinimum": true 28 | }, 29 | "tests": [ 30 | { 31 | "description": "above the minimum is still valid", 32 | "data": 1.2, 33 | "valid": true 34 | }, 35 | { 36 | "description": "boundary point is invalid", 37 | "data": 1.1, 38 | "valid": false 39 | } 40 | ] 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/optional/zeroTerminatedFloats.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "some languages do not distinguish between different types of numeric value", 4 | "schema": { 5 | "type": "integer" 6 | }, 7 | "tests": [ 8 | { 9 | "description": "a float is not an integer even without fractional part", 10 | "data": 1.0, 11 | "valid": false 12 | } 13 | ] 14 | } 15 | ] 16 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/pattern.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "pattern validation", 4 | "schema": {"pattern": "^a*$"}, 5 | "tests": [ 6 | { 7 | "description": "a matching pattern is valid", 8 | "data": "aaa", 9 | "valid": true 10 | }, 11 | { 12 | "description": "a non-matching pattern is invalid", 13 | "data": "abc", 14 | "valid": false 15 | }, 16 | { 17 | "description": "ignores non-strings", 18 | "data": true, 19 | "valid": true 20 | } 21 | ] 22 | }, 23 | { 24 | "description": "pattern is not anchored", 25 | "schema": {"pattern": "a+"}, 26 | "tests": [ 27 | { 28 | "description": "matches a substring", 29 | "data": "xxaayy", 30 | "valid": true 31 | } 32 | ] 33 | } 34 | ] 35 | -------------------------------------------------------------------------------- /src/NJsonSchema.Demo/Tests/required.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "description": "required validation", 4 | "schema": { 5 | "properties": { 6 | "foo": {}, 7 | "bar": {} 8 | }, 9 | "required": ["foo"] 10 | }, 11 | "tests": [ 12 | { 13 | "description": "present required property is valid", 14 | "data": {"foo": 1}, 15 | "valid": true 16 | }, 17 | { 18 | "description": "non-present required property is invalid", 19 | "data": {"bar": 1}, 20 | "valid": false 21 | } 22 | ] 23 | }, 24 | { 25 | "description": "required default validation", 26 | "schema": { 27 | "properties": { 28 | "foo": {} 29 | } 30 | }, 31 | "tests": [ 32 | { 33 | "description": "not required by default", 34 | "data": {}, 35 | "valid": true 36 | } 37 | ] 38 | } 39 | ] 40 | -------------------------------------------------------------------------------- /src/NJsonSchema.NewtonsoftJson.Tests/Generation/RecordTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.NewtonsoftJson.Generation; 2 | using Xunit; 3 | 4 | namespace NJsonSchema.NewtonsoftJson.Tests.Generation 5 | { 6 | public class RecordTests 7 | { 8 | public record Address 9 | { 10 | public string Street { get; set; } 11 | } 12 | 13 | [Fact] 14 | public void Should_have_only_one_property() 15 | { 16 | // Arrange 17 | 18 | // Act 19 | var schema = NewtonsoftJsonSchemaGenerator.FromType
(); 20 | var data = schema.ToJson(); 21 | 22 | // Assert 23 | Assert.Single(schema.Properties); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/NJsonSchema.NewtonsoftJson.Tests/Generation/StructTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using NJsonSchema.Annotations; 3 | using NJsonSchema.NewtonsoftJson.Generation; 4 | using Xunit; 5 | 6 | namespace NJsonSchema.NewtonsoftJson.Tests.Generation 7 | { 8 | public class StructTests 9 | { 10 | [JsonSchema("UserDefinedStruct")] 11 | public struct UserDefinedStruct 12 | { 13 | } 14 | 15 | public class UserDefinedClass 16 | { 17 | [JsonProperty] 18 | public readonly UserDefinedStruct NonNullableField; 19 | 20 | [JsonProperty] 21 | public readonly UserDefinedStruct? NullableField; 22 | } 23 | 24 | [Fact] 25 | public void Should_have_a_shared_struct_schema() 26 | { 27 | // Arrange 28 | 29 | // Act 30 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 31 | var data = schema.ToJson(); 32 | 33 | // Assert 34 | Assert.Single(schema.Definitions); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /src/NJsonSchema.NewtonsoftJson.Tests/NJsonSchema.NewtonsoftJson.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | $(TargetFrameworks);net472 6 | false 7 | disable 8 | latest-Minimal 9 | 10 | 11 | 12 | bin\Debug\$(TargetFramework)\NJsonSchema.Tests.xml 13 | $(NoWarn),618,1587,1998,1591 14 | 15 | $(NoWarn),CA1707 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.NewtonsoftJson.Converters 10 | { 11 | /// Defines a child class in the inheritance chain. 12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] 13 | public class JsonInheritanceAttribute : Attribute 14 | { 15 | /// Initializes a new instance of the class. 16 | /// The discriminator key. 17 | /// The child class type. 18 | public JsonInheritanceAttribute(string key, Type type) 19 | { 20 | Key = key; 21 | Type = type; 22 | } 23 | 24 | /// Gets the discriminator key. 25 | public string Key { get; } 26 | 27 | /// Gets the child class type. 28 | public Type Type { get; } 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema.NewtonsoftJson/NJsonSchema.NewtonsoftJson.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net462;net8.0 5 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/NJsonSchema.NewtonsoftJson/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.NewtonsoftJson/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/AbstractGenerationTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.NewtonsoftJson.Generation; 2 | using Xunit; 3 | 4 | namespace NJsonSchema.Tests.Generation 5 | { 6 | public class AbstractGenerationTests 7 | { 8 | public abstract class AbstractClass 9 | { 10 | public string Foo { get; set; } 11 | } 12 | 13 | [Fact] 14 | public async Task When_class_is_abstract_then_is_abstract_is_true() 15 | { 16 | // Act 17 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 18 | var json = schema.ToJson(); 19 | 20 | // Assert 21 | Assert.Contains("x-abstract", json); 22 | Assert.True(schema.IsAbstract); 23 | } 24 | 25 | public class NotAbstractClass 26 | { 27 | public string Foo { get; set; } 28 | } 29 | 30 | [Fact] 31 | public async Task When_class_is_not_abstract_then_is_abstract_is_false() 32 | { 33 | // Act 34 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 35 | var json = schema.ToJson(); 36 | 37 | // Assert 38 | Assert.DoesNotContain("x-abstract", json); 39 | Assert.False(schema.IsAbstract); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/DefaultSchemaNameGeneratorTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.Generation; 2 | using Xunit; 3 | 4 | namespace NJsonSchema.Tests.Generation 5 | { 6 | public class DefaultSchemaNameGeneratorTests 7 | { 8 | [Theory] 9 | [InlineData(typeof(Dictionary), "DictionaryOfStringAndInteger")] 10 | [InlineData(typeof(Dictionary), "DictionaryOfBooleanAndLong")] 11 | [InlineData(typeof(Dictionary), "DictionaryOfDecimalAndShort")] 12 | [InlineData(typeof(Dictionary), "DictionaryOfGuidAndDateTime")] 13 | [InlineData(typeof(Dictionary), "DictionaryOfNullableDecimalAndNullableShort")] 14 | public void When_display_name_is_retrieved_then_string_is_correct(Type type, string expectedName) 15 | { 16 | // Act 17 | var generator = new DefaultSchemaNameGenerator(); 18 | var name = generator.Generate(type); 19 | 20 | // Assert 21 | Assert.Equal(expectedName, name); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/ExceptionTypeTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Generation 6 | { 7 | public class ExceptionTypeTests 8 | { 9 | public class MyException : Exception 10 | { 11 | [JsonProperty("foo")] 12 | public string Foo { get; set; } 13 | } 14 | 15 | [Fact] 16 | public async Task When_exception_schema_is_generated_then_special_properties_are_generated_and_JsonProperty_attribute_used() 17 | { 18 | // Arrange 19 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 20 | var json = schema.ToJson(); 21 | 22 | // Act 23 | var exceptionSchema = schema.InheritedSchema.ActualSchema; 24 | 25 | // Assert 26 | Assert.True(schema.ActualProperties.ContainsKey("foo")); 27 | Assert.True(exceptionSchema.ActualProperties.ContainsKey("InnerException")); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/ExcplicitInterfacePropertyTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Generation 6 | { 7 | public class ExcplicitInterfacePropertyTests 8 | { 9 | public interface IFoo 10 | { 11 | string Prop { get; set; } 12 | } 13 | 14 | public class Foo : IFoo 15 | { 16 | string IFoo.Prop { get; set; } 17 | 18 | public string MyProp { get; set; } 19 | } 20 | 21 | [Fact] 22 | public void When_a_property_is_explicit_interface_then_it_is_not_serialized() 23 | { 24 | // Arrange 25 | var foo = new Foo(); 26 | ((IFoo)foo).Prop = "foobar"; 27 | 28 | // Act 29 | var json = JsonConvert.SerializeObject(foo); 30 | 31 | // Assert 32 | Assert.Equal(@"{""MyProp"":null}", json); 33 | } 34 | 35 | [Fact] 36 | public async Task When_a_property_is_explicit_interface_then_it_is_not_added_to_schema() 37 | { 38 | // Arrange 39 | 40 | // Act 41 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 42 | 43 | // Assert 44 | Assert.Single(schema.Properties); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/ExtensionDataGenerationTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Generation 6 | { 7 | public class ExtensionDataGenerationTests 8 | { 9 | public class ClassWithExtensionData 10 | { 11 | public string Foo { get; set; } 12 | 13 | [JsonExtensionData] 14 | public IDictionary ExtensionData { get; set; } 15 | } 16 | 17 | [Fact] 18 | public async Task When_class_has_property_with_JsonExtensionDataAttribute_on_property_then_AdditionalProperties_schema_is_set() 19 | { 20 | // Act 21 | var schema = NewtonsoftJsonSchemaGenerator.FromType(new NewtonsoftJsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); 22 | var json = schema.ToJson(); 23 | 24 | // Assert 25 | Assert.Single(schema.ActualProperties); 26 | Assert.True(schema.AllowAdditionalProperties); 27 | Assert.True(schema.AdditionalPropertiesSchema.ActualSchema.IsAnyType); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/FieldGenerationTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.NewtonsoftJson.Generation; 2 | using Xunit; 3 | 4 | namespace NJsonSchema.Tests.Generation 5 | { 6 | public class FieldGenerationTests 7 | { 8 | public class MyTest 9 | { 10 | public string MyField; 11 | } 12 | 13 | [Fact] 14 | public async Task When_public_field_is_available_then_it_is_added_as_property() 15 | { 16 | // Arrange 17 | 18 | 19 | // Act 20 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 21 | var json = schema.ToJson(); 22 | 23 | // Assert 24 | Assert.True(schema.Properties["MyField"].Type.HasFlag(JsonObjectType.String)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/GenericTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.NewtonsoftJson.Generation; 2 | using System.Collections; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Generation 6 | { 7 | public class GenericTests 8 | { 9 | public class Smth : IEnumerable 10 | { 11 | IEnumerator IEnumerable.GetEnumerator() 12 | { 13 | return GetEnumerator(); 14 | } 15 | 16 | public IEnumerator GetEnumerator() 17 | { 18 | throw new NotImplementedException(); 19 | } 20 | } 21 | 22 | [Fact] 23 | public async Task When_class_inherits_from_IEnumerable_then_it_should_become_a_json_array_type() 24 | { 25 | // Arrange 26 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 27 | 28 | // Act 29 | var json = schema.ToJson(); 30 | 31 | // Assert 32 | Assert.Equal(JsonObjectType.Array, schema.Type); 33 | Assert.Equal(JsonObjectType.String, schema.Item.Type); 34 | } 35 | 36 | public class A 37 | { 38 | public T B { get; set; } 39 | } 40 | 41 | [Fact] 42 | public async Task When_open_generic_type_is_generated_then_no_exception_is_thrown() 43 | { 44 | // Arrange 45 | var schema = NewtonsoftJsonSchemaGenerator.FromType(typeof(A<>)); 46 | 47 | // Act 48 | var json = schema.ToJson(); 49 | 50 | // Assert 51 | Assert.NotNull(json); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/InterfaceTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.NewtonsoftJson.Generation; 2 | using Xunit; 3 | 4 | namespace NJsonSchema.Tests.Generation 5 | { 6 | public class InterfaceTests 7 | { 8 | public class BusinessCategory : ICategory 9 | { 10 | public string Key { get; set; } 11 | 12 | public string DisplayName { get; set; } 13 | 14 | public IEnumerable Children { get; set; } 15 | 16 | public IEnumerable Elements { get; set; } 17 | } 18 | 19 | public interface ICategory 20 | { 21 | string DisplayName { get; set; } 22 | 23 | string Key { get; set; } 24 | } 25 | 26 | [Fact] 27 | public async Task When_class_inherits_from_interface_then_properties_for_interface_are_generated() 28 | { 29 | // Arrange 30 | 31 | // Act 32 | var schema = NewtonsoftJsonSchemaGenerator.FromType(new NewtonsoftJsonSchemaGeneratorSettings 33 | { 34 | GenerateAbstractProperties = true 35 | }); 36 | 37 | var json = schema.ToJson(); 38 | 39 | // Assert 40 | Assert.Equal(2, schema.Definitions["ICategory"].Properties.Count); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/RecordTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NJsonSchema.Tests.Generation 4 | { 5 | public class RecordTests 6 | { 7 | public record Address 8 | { 9 | public string Street { get; set; } 10 | } 11 | 12 | [Fact] 13 | public void Should_have_only_one_property() 14 | { 15 | // Arrange 16 | 17 | // Act 18 | var schema = JsonSchema.FromType
(); 19 | var data = schema.ToJson(); 20 | 21 | var add = new Address(); 22 | 23 | // Assert 24 | Assert.Single(schema.Properties); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/SchemaProcessorTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.Annotations; 2 | using NJsonSchema.Generation; 3 | using NJsonSchema.NewtonsoftJson.Generation; 4 | using Xunit; 5 | 6 | namespace NJsonSchema.Tests.Generation 7 | { 8 | public class SchemaProcessorTests 9 | { 10 | public class MyTestSchemaProcessor : ISchemaProcessor 11 | { 12 | private readonly object _example; 13 | 14 | public MyTestSchemaProcessor(object example) 15 | { 16 | _example = example; 17 | } 18 | 19 | public void Process(SchemaProcessorContext context) 20 | { 21 | context.Schema.Example = _example; 22 | } 23 | } 24 | 25 | [JsonSchemaProcessor(typeof(MyTestSchemaProcessor), "example123")] 26 | public class ClassWithSchemaProcessor 27 | { 28 | public string Foo { get; set; } 29 | } 30 | 31 | [Fact] 32 | public void When_class_has_schema_processor_attribute_then_it_is_processed() 33 | { 34 | // Act 35 | var schema = NewtonsoftJsonSchemaGenerator.FromType(new NewtonsoftJsonSchemaGeneratorSettings()); 36 | var data = schema.ToJson(); 37 | 38 | // Assert 39 | Assert.Equal("example123", schema.Example); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/ShouldSerializeTests.cs: -------------------------------------------------------------------------------- 1 | using NJsonSchema.NewtonsoftJson.Generation; 2 | using Xunit; 3 | 4 | namespace NJsonSchema.Tests.Generation 5 | { 6 | public class ShouldSerializeTests 7 | { 8 | public class Test 9 | { 10 | public string Name { get; set; } 11 | 12 | public bool ShouldSerializeName() 13 | { 14 | return !string.IsNullOrEmpty(Name); 15 | } 16 | } 17 | 18 | [Fact] 19 | public void When_ShouldSerialize_method_exists_then_schema_is_generated() 20 | { 21 | // Arrange 22 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 23 | 24 | // Act 25 | 26 | 27 | // Assert 28 | Assert.NotNull(schema); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Generation/XmlDocsTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using NJsonSchema.NewtonsoftJson.Generation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Generation 6 | { 7 | public class XmlDocsTests 8 | { 9 | /// Foobar. 10 | /// 11 | /// { "foo": "bar" } 12 | /// 13 | public abstract class AbstractClass 14 | { 15 | /// 16 | /// { "abc": "def" } 17 | /// 18 | public string Foo { get; set; } 19 | 20 | /// Bar. 21 | public string Bar { get; set; } 22 | } 23 | 24 | [Fact] 25 | public async Task When_example_xml_docs_is_defined_then_examples_can_be_defined() 26 | { 27 | // Act 28 | var schema = NewtonsoftJsonSchemaGenerator.FromType(); 29 | var json = schema.ToJson(Formatting.None); 30 | 31 | // Assert 32 | Assert.Contains(@"Foobar.", json); 33 | Assert.Contains(@"""x-example"":{""foo"":""bar""}", json); 34 | Assert.Contains(@"""x-example"":{""abc"":""def""}", json); 35 | Assert.Contains(@"""x-example"":""Bar.""", json); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/animal.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "bar": { 5 | "name": { 6 | "type": "string" 7 | } 8 | } 9 | }, 10 | "definitions": { 11 | "SubAnimal": { 12 | "type": "object" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "myInt": { 3 | "type": "integer" 4 | }, 5 | "myBool": { 6 | "type": "boolean" 7 | } 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/dir_with_#/first.json: -------------------------------------------------------------------------------- 1 | { 2 | "$ref": "./second.json#/myInt" 3 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/dir_with_#/second.json: -------------------------------------------------------------------------------- 1 | { 2 | "myInt": { 3 | "type": "integer" 4 | } 5 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/schema_with_collection_reference.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "bar": { 5 | "$ref": "./collection.json#/myBool" 6 | }, 7 | "foo": { 8 | "$ref": "#/definitions/collection/myInt" 9 | } 10 | }, 11 | "definitions": { 12 | "collection": { 13 | "$ref": "./collection.json" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/schema_with_indirect_reference.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "foo": { 5 | "$ref": "#/definitions/FooAnimal" 6 | } 7 | }, 8 | "definitions": { 9 | "FooAnimal": { 10 | "$ref": "./animal.json" 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/schema_with_indirect_subreference.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "foo": { 5 | "$ref": "./animal.json#/definitions/SubAnimal" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/References/LocalReferencesTests/schema_with_reference.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "foo": { 5 | "$ref": "./animal.json" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatEmailTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatEmailTests 8 | { 9 | [Fact] 10 | public void When_format_email_incorrect_then_validation_succeeds() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.Email; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.EmailExpected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_email_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.Email; 33 | 34 | var token = new JValue("mail@rsuter.com"); 35 | 36 | // Act 37 | var errors = schema.Validate(token); 38 | 39 | // Assert 40 | Assert.Empty(errors); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatGuidTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatGuidTests 8 | { 9 | [Fact] 10 | public void When_format_guid_incorrect_then_validation_succeeds() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.Guid; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.GuidExpected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_guid_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.Guid; 33 | 34 | var guid = Guid.NewGuid().ToString(); 35 | var token = new JValue(guid); 36 | 37 | // Act 38 | var errors = schema.Validate(token); 39 | 40 | // Assert 41 | Assert.Empty(errors); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatHostnameTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatHostnameTests 8 | { 9 | [Fact] 10 | public void When_format_hostname_incorrect_then_validation_succeeds() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.Hostname; 16 | 17 | var token = new JValue("foo:bar"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.HostnameExpected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_hostname_is_ip_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.Hostname; 33 | 34 | var token = new JValue("rsuter.com"); 35 | 36 | // Act 37 | var errors = schema.Validate(token); 38 | 39 | // Assert 40 | Assert.Empty(errors); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatIpV4Tests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatIpV4Tests 8 | { 9 | [Fact] 10 | public void When_format_ipv4_incorrect_then_validation_succeeds() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.IpV4; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.IpV4Expected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_ipv4_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.IpV4; 33 | 34 | var token = new JValue("192.168.0.1"); 35 | 36 | // Act 37 | var errors = schema.Validate(token); 38 | 39 | // Assert 40 | Assert.Empty(errors); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatIpV6Tests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatIpV6Tests 8 | { 9 | [Fact] 10 | public void When_format_ipv6_incorrect_then_validation_fails() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.IpV6; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.IpV6Expected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_ipv6_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.IpV6; 33 | 34 | var token = new JValue("::1"); 35 | 36 | // Act 37 | var errors = schema.Validate(token); 38 | 39 | // Assert 40 | Assert.Empty(errors); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatTimeSpanTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatTimeSpanTests 8 | { 9 | [Fact] 10 | public void When_format_time_span_incorrect_then_validation_fails() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.TimeSpan; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.TimeSpanExpected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_time_span_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.TimeSpan; 33 | 34 | var token = new JValue("1:30:45"); 35 | 36 | // Act 37 | var errors = schema.Validate(token); 38 | 39 | // Assert 40 | Assert.Empty(errors); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatUriTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatUriTests 8 | { 9 | [Fact] 10 | public void When_format_uri_incorrect_then_validation_succeeds() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.Uri; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.UriExpected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_uri_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.Uri; 33 | 34 | var token = new JValue("http://rsuter.com"); 35 | 36 | // Act 37 | var errors = schema.Validate(token); 38 | 39 | // Assert 40 | Assert.Empty(errors); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/FormatUuidTests.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | using NJsonSchema.Validation; 3 | using Xunit; 4 | 5 | namespace NJsonSchema.Tests.Validation 6 | { 7 | public class FormatUuidTests 8 | { 9 | [Fact] 10 | public void When_format_uuid_incorrect_then_validation_succeeds() 11 | { 12 | // Arrange 13 | var schema = new JsonSchema(); 14 | schema.Type = JsonObjectType.String; 15 | schema.Format = JsonFormatStrings.Uuid; 16 | 17 | var token = new JValue("test"); 18 | 19 | // Act 20 | var errors = schema.Validate(token); 21 | 22 | // Assert 23 | Assert.Equal(ValidationErrorKind.UuidExpected, errors.First().Kind); 24 | } 25 | 26 | [Fact] 27 | public void When_format_uuid_correct_then_validation_succeeds() 28 | { 29 | // Arrange 30 | var schema = new JsonSchema(); 31 | schema.Type = JsonObjectType.String; 32 | schema.Format = JsonFormatStrings.Uuid; 33 | 34 | var uuid = Guid.NewGuid().ToString(); 35 | var token = new JValue(uuid); 36 | 37 | // Act 38 | var errors = schema.Validate(token); 39 | 40 | // Assert 41 | Assert.Empty(errors); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Tests/Validation/UniqueItemsTests.cs: -------------------------------------------------------------------------------- 1 | using Xunit; 2 | 3 | namespace NJsonSchema.Tests.Validation 4 | { 5 | public class UniqueItemsTests 6 | { 7 | [Fact] 8 | public async Task When_unique_items_is_set_and_items_are_objects_then_validation_works() 9 | { 10 | // Arrange 11 | var jsonSchema = @"{ 12 | ""$schema"": ""http://json-schema.org/draft-04/schema#"", 13 | ""title"": ""Config"", 14 | ""type"": ""array"", 15 | ""uniqueItems"": true, 16 | ""items"": { 17 | ""title"": ""KeyValue Pair"", 18 | ""type"": ""object"", 19 | ""properties"": { 20 | ""key"": { 21 | ""title"": ""Key"", 22 | ""type"": ""string"", 23 | ""minLength"": 1 24 | }, 25 | ""value"": { 26 | ""title"": ""Value"", 27 | ""type"": ""string"", 28 | ""minLength"": 1 29 | } 30 | } 31 | } 32 | }"; 33 | 34 | var jsonData = @"[{ 35 | ""key"": ""a"", 36 | ""value"": ""b"" 37 | }, 38 | { 39 | ""key"": ""a"", 40 | ""value"": ""b"" 41 | }]"; 42 | 43 | // Act 44 | var schema = await JsonSchema.FromJsonAsync(jsonSchema); 45 | var errors = schema.Validate(jsonData).ToList(); 46 | 47 | // Assert 48 | Assert.Single(errors); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/NJsonSchema.Yaml.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | $(TargetFrameworks);net472 6 | false 7 | disable 8 | latest-Minimal 9 | $(NoWarn);1591 10 | 11 | 12 | 13 | 14 | $(NoWarn),CA1707 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "myInt": { 3 | "type": "integer" 4 | }, 5 | "myBool": { 6 | "type": "boolean" 7 | } 8 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/collection.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | myInt: 3 | type: integer 4 | myBool: 5 | type: boolean 6 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/common-items/headers.yaml: -------------------------------------------------------------------------------- 1 | components: 2 | headers: 3 | Content-Language: 4 | description: |- 5 | The Content-Language header field describes the natural language(s) 6 | of the intended audience for the representation. Note that this 7 | might not be equivalent to all the languages used within the 8 | representation. 9 | 10 | Reference: https://tools.ietf.org/html/rfc7231#section-3.1.3.2 11 | schema: 12 | type: string 13 | example: 'en' -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/common-items/parameters.yaml: -------------------------------------------------------------------------------- 1 | components: 2 | parameters: 3 | Accept-Language: 4 | name: Accept-Language 5 | in: header 6 | description: |- 7 | The Accept-Language 8 | header field can be used by user agents to 9 | indicate the set of natural languages that are preferred in the 10 | response. Language tags are defined in RFC 5646. If none of the 11 | languages given are supported, a default language will be returned. 12 | schema: 13 | type: string 14 | example: 'en-US' 15 | Range: 16 | name: Range 17 | in: header 18 | description: |- 19 | The Range 20 | header field on a request modifies the method semantics to request 21 | transfer of only one or more subranges of the selected representation 22 | data, rather than the entire selected representation data. 23 | 24 | The Range unit `bytes` is supported to represent byte ranges of the 25 | page or document of the specific rendition's content. 26 | 27 | For the cases where the Range header is omitted, the full document or page will be 28 | returned. 29 | schema: 30 | type: string 31 | example: 'bytes 1-1000' -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/common-items/responses.yaml: -------------------------------------------------------------------------------- 1 | components: 2 | responses: 3 | 401-GENERIC-RESPONSE: 4 | description: |- 5 | Response when the user does not supply valid authorization credentials. 6 | content: 7 | application/problem+json: 8 | schema: 9 | $ref: 'schemas.yaml#/components/schemas/Problem-Detail' 10 | example: 11 | type: 'https://example.net/unauthorized' 12 | title: 'Unauthorized' 13 | status: 401 14 | detail: 'Not authorized to perform this action.' 15 | instance: '/example-resource' -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/json_schema_with_json_reference.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "bar": { 5 | "$ref": "./collection.json#/myBool" 6 | }, 7 | "foo": { 8 | "$ref": "#/definitions/collection/myInt" 9 | } 10 | }, 11 | "definitions": { 12 | "collection": { 13 | "$ref": "./collection.json" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/json_schema_with_yaml_reference.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "object", 3 | "properties": { 4 | "bar": { 5 | "$ref": "./collection.yaml#/myBool" 6 | }, 7 | "foo": { 8 | "$ref": "#/definitions/collection/myInt" 9 | } 10 | }, 11 | "definitions": { 12 | "collection": { 13 | "$ref": "./collection.yaml" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/subdir_spec/enums/TaskExecutionStatusEnum.yaml: -------------------------------------------------------------------------------- 1 | TaskExecutionStatusEnum: 2 | description: |- 3 | Status of a task execution 4 | type: string 5 | enum: 6 | - Completed 7 | - Failed 8 | example: Completed 9 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/subdir_spec/models/ExecuteTaskResultModel.yaml: -------------------------------------------------------------------------------- 1 | ExecuteTaskResultModel: 2 | description: |- 3 | Contains the status of an ad hoc or system task executon. 4 | type: object 5 | properties: 6 | status: 7 | $ref: '../enums/TaskExecutionStatusEnum.yaml#/TaskExecutionStatusEnum' 8 | discriminator: 9 | propertyName: status 10 | mapping: 11 | Completed: '../yaml_spec_with_yaml_schema_with_relative_subdir_refs.yaml#/components/schemas/ExecuteTaskCompletedModel' 12 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/subdir_spec/models/LifeCycleCollectionModel.yaml: -------------------------------------------------------------------------------- 1 | LifeCycleCollectionModel: 2 | description: |- 3 | A list of life cycles. 4 | properties: 5 | items: 6 | description: List of life cycles. 7 | type: array 8 | items: 9 | $ref: 'LifeCycleModel.yaml#/LifeCycleModel' 10 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/subdir_spec/models/LifeCycleModel.yaml: -------------------------------------------------------------------------------- 1 | LifeCycleModel: 2 | description: |- 3 | Gets the life cycle with the associated id. 4 | properties: 5 | id: 6 | description: |- 7 | The unique identifier of the life cycle. 8 | type: string 9 | example: 101 10 | systemName: 11 | description: |- 12 | The untranslated system name of the life cycle. Localization is controlled by the Accept-Language header and the 13 | language of the response is represented by the Content-Language header. 14 | type: string 15 | example: AR - Outstanding Invoices 16 | name: 17 | description: |- 18 | The localized name of the life cycle. 19 | type: string 20 | example: AR - Outstanding Invoices 21 | smallImageID: 22 | description: |- 23 | The document ID in SYS System Icons or SYS System Bitmaps which is the image for the item. 24 | type: string 25 | example: 201 26 | helpText: 27 | description: |- 28 | The life cycle help text. 29 | type: string 30 | example: |- 31 | AR Invoices are automatically entered into the workflow process when they are generated. Invoices remain in this workflow until 32 | a corresponding payment is made to the invoice. 33 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/yaml_schema_with_json_reference.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | type: object 3 | properties: 4 | bar: 5 | "$ref": "./collection.json#/myBool" 6 | foo: 7 | "$ref": "#/definitions/collection/myInt" 8 | definitions: 9 | collection: 10 | "$ref": "./collection.json" 11 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml.Tests/References/YamlReferencesTest/yaml_schema_with_yaml_reference.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | type: object 3 | properties: 4 | bar: 5 | "$ref": "./collection.yaml#/myBool" 6 | foo: 7 | "$ref": "#/definitions/collection/myInt" 8 | definitions: 9 | collection: 10 | "$ref": "./collection.yaml" 11 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml/NJsonSchema.Yaml.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net462;net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/NJsonSchema.Yaml/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.Yaml/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema.snk -------------------------------------------------------------------------------- /src/NJsonSchema/Converters/JsonInheritanceAttribute.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Converters 10 | { 11 | /// Defines a child class in the inheritance chain. 12 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] 13 | public class JsonInheritanceAttribute : Attribute 14 | { 15 | /// Initializes a new instance of the class. 16 | /// The discriminator key. 17 | /// The child class type. 18 | public JsonInheritanceAttribute(string key, Type type) 19 | { 20 | Key = key; 21 | Type = type; 22 | } 23 | 24 | /// Gets the discriminator key. 25 | public string Key { get; } 26 | 27 | /// Gets the child class type. 28 | public Type Type { get; } 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/ISchemaNameGenerator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Generation 10 | { 11 | /// The schema name generator. 12 | public interface ISchemaNameGenerator 13 | { 14 | /// Generates the name of the JSON Schema for the given type. 15 | /// The type. 16 | /// The new name. 17 | string Generate(Type type); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/ISchemaProcessor.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Generation 10 | { 11 | /// The schema processor interface. 12 | public interface ISchemaProcessor 13 | { 14 | /// Processes the specified JSON Schema. 15 | /// The schema context. 16 | void Process(SchemaProcessorContext context); 17 | } 18 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/IXmlDocsSettings.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Namotion.Reflection; 10 | 11 | namespace NJsonSchema.Generation 12 | { 13 | /// The XML Docs related settings. 14 | public interface IXmlDocsSettings 15 | { 16 | /// Gets or sets a value indicating whether to read XML Docs (default: true). 17 | bool UseXmlDocumentation { get; } 18 | 19 | /// Gets or sets a value indicating whether tho resolve the XML Docs from the NuGet cache or .NET SDK directory (default: true). 20 | bool ResolveExternalXmlDocumentation { get; } 21 | 22 | /// Gets or sets the XML Docs formatting (default: None). 23 | XmlDocsFormattingMode XmlDocumentationFormatting { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/ReferenceTypeNullHandling.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Generation 10 | { 11 | /// Specifies the default null handling for reference types when no nullability information is available. 12 | public enum ReferenceTypeNullHandling 13 | { 14 | /// Reference types are nullable by default (C# default). 15 | Null, 16 | 17 | /// Reference types cannot be null by default. 18 | NotNull 19 | } 20 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/SystemTextJsonSchemaGeneratorSettings.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json; 10 | using System.Text.Json; 11 | 12 | namespace NJsonSchema.Generation 13 | { 14 | /// 15 | /// 16 | /// 17 | public class SystemTextJsonSchemaGeneratorSettings : JsonSchemaGeneratorSettings 18 | { 19 | /// 20 | /// 21 | /// 22 | public SystemTextJsonSchemaGeneratorSettings() : base(new SystemTextJsonReflectionService()) 23 | { 24 | } 25 | 26 | /// Gets or sets the System.Text.Json serializer options. 27 | [JsonIgnore] 28 | public JsonSerializerOptions SerializerOptions { get; set; } = new JsonSerializerOptions(); 29 | } 30 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/TypeMappers/ITypeMapper.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.Generation.TypeMappers 10 | { 11 | /// Maps .NET type to a generated JSON Schema. 12 | public interface ITypeMapper 13 | { 14 | /// Gets the mapped type. 15 | Type MappedType { get; } 16 | 17 | /// Gets a value indicating whether to use a JSON Schema reference for the type. 18 | bool UseReference { get; } 19 | 20 | /// Gets the schema for the mapped type. 21 | /// The schema. 22 | /// The context. 23 | void GenerateSchema(JsonSchema schema, TypeMapperContext context); 24 | } 25 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Generation/XmlDocsSettingsExtensions.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Namotion.Reflection; 10 | 11 | namespace NJsonSchema.Generation 12 | { 13 | /// 14 | /// XML Documentation settings extensions. 15 | /// 16 | public static class XmlDocsSettingsExtensions 17 | { 18 | /// 19 | /// Converts a settings to options. 20 | /// 21 | /// The settings. 22 | /// The options. 23 | public static XmlDocsOptions GetXmlDocsOptions(this IXmlDocsSettings settings) 24 | { 25 | return new XmlDocsOptions 26 | { 27 | ResolveExternalXmlDocs = settings.ResolveExternalXmlDocumentation, 28 | FormattingMode = settings.XmlDocumentationFormatting 29 | }; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/NJsonSchema/IDocumentPathProvider.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json; 10 | 11 | namespace NJsonSchema 12 | { 13 | /// Provides a property to get a documents path or base URI. 14 | public interface IDocumentPathProvider 15 | { 16 | /// Gets the document path (URI or file path). 17 | [JsonIgnore] 18 | string? DocumentPath { get; set; } 19 | } 20 | } -------------------------------------------------------------------------------- /src/NJsonSchema/IJsonExtensionObject.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema 10 | { 11 | /// The base JSON interface with extension data. 12 | public interface IJsonExtensionObject 13 | { 14 | /// Gets or sets the extension data (i.e. additional properties which are not directly defined by the JSON object). 15 | IDictionary? ExtensionData { get; set; } 16 | } 17 | } -------------------------------------------------------------------------------- /src/NJsonSchema/ITypeNameGenerator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema 10 | { 11 | /// Generates the type name for a given . 12 | public interface ITypeNameGenerator 13 | { 14 | /// Generates the type name. 15 | /// The property. 16 | /// The type name hint (the property name or definition key). 17 | /// The reserved type names. 18 | /// The new name. 19 | string Generate(JsonSchema schema, string? typeNameHint, IEnumerable reservedTypeNames); 20 | } 21 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Infrastructure/Polyfills.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable once CheckNamespace 2 | 3 | namespace NJsonSchema; 4 | 5 | internal static class Polyfills 6 | { 7 | #if NETFRAMEWORK || NETSTANDARD2_0 8 | [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] 9 | internal static bool Contains(this string source, char c) => source.IndexOf(c) != -1; 10 | 11 | [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] 12 | internal static bool StartsWith(this string source, char c) => source.Length > 0 && source[0] == c; 13 | 14 | [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] 15 | internal static bool EndsWith(this string s, char c) => s.Length > 0 && s[^1] == c; 16 | #endif 17 | 18 | #if NETFRAMEWORK 19 | [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] 20 | internal static bool Contains(this System.ReadOnlySpan source, string c) => System.MemoryExtensions.IndexOf(source, c) != -1; 21 | #endif 22 | } -------------------------------------------------------------------------------- /src/NJsonSchema/NJsonSchema.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $author$ 7 | $description$ 8 | json schema validation generator .net 9 | http://NJsonSchema.org 10 | MIT 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/NJsonSchema/NuGetIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RicoSuter/NJsonSchema/39da52cc37c1aedb7a6c41ff0e25d547bd586c8b/src/NJsonSchema/NuGetIcon.png -------------------------------------------------------------------------------- /src/NJsonSchema/References/IJsonReference.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json; 10 | 11 | namespace NJsonSchema.References 12 | { 13 | /// A JSON object which may reference other objects with $ref. 14 | /// The methods should be implemented explicitly to hide them from the API. 15 | public interface IJsonReference : IJsonReferenceBase 16 | { 17 | /// Gets the actual referenced object, either this or the reference object. 18 | [JsonIgnore] 19 | IJsonReference ActualObject { get; } 20 | 21 | /// Gets the parent object which may be the root. 22 | [JsonIgnore] 23 | object? PossibleRoot { get; } 24 | } 25 | } -------------------------------------------------------------------------------- /src/NJsonSchema/References/IJsonReferenceBase.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json; 10 | 11 | namespace NJsonSchema.References 12 | { 13 | /// A JSON object which may reference other objects with $ref. 14 | public interface IJsonReferenceBase : IDocumentPathProvider 15 | { 16 | /// Gets or sets the type reference path ($ref). 17 | [JsonProperty("$ref", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] 18 | string? ReferencePath { get; set; } 19 | 20 | /// Gets or sets the referenced object. 21 | [JsonIgnore] 22 | IJsonReference? Reference { get; set; } 23 | } 24 | } -------------------------------------------------------------------------------- /src/NJsonSchema/References/JsonReferenceExtensions.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema.References 10 | { 11 | /// Extensions to work with . 12 | public static class JsonReferenceExtensions 13 | { 14 | /// Finds the root parent of this schema. 15 | /// The parent schema or this when this is the root. 16 | public static object? FindParentDocument(this IJsonReference obj) 17 | { 18 | if (obj.DocumentPath != null) 19 | { 20 | return obj; 21 | } 22 | 23 | var parent = obj.PossibleRoot; 24 | if (parent == null) 25 | { 26 | return obj; 27 | } 28 | 29 | while (parent is IJsonReference { PossibleRoot: not null }) 30 | { 31 | parent = ((IJsonReference)parent!).PossibleRoot; 32 | if (parent is IDocumentPathProvider pathProvider && pathProvider.DocumentPath != null) 33 | { 34 | return parent; 35 | } 36 | } 37 | 38 | return parent; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/NJsonSchema/SampleJsonDataGeneratorSettings.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema 10 | { 11 | /// Settings for generating sample json data. 12 | public class SampleJsonDataGeneratorSettings 13 | { 14 | /// Gets or sets a value indicating whether to generate optional properties (default: true). 15 | public bool GenerateOptionalProperties { get; set; } = true; 16 | 17 | /// Gets or sets a value indicating the max level of recursion the generator is allowed to perform (default: 3) 18 | public int MaxRecursionLevel { get; set; } = 3; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/NJsonSchema/SampleJsonSchemaGeneratorSettings.cs: -------------------------------------------------------------------------------- 1 | namespace NJsonSchema 2 | { 3 | /// 4 | /// Settings for generating sample json schema 5 | /// 6 | public class SampleJsonSchemaGeneratorSettings 7 | { 8 | /// 9 | /// Gets or sets a value indicating whether to generate optional properties (default: ). 10 | /// 11 | public SchemaType SchemaType { get; set; } = SchemaType.JsonSchema; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/NJsonSchema/SchemaType.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | namespace NJsonSchema 10 | { 11 | /// Defines how to express the nullability of a property. 12 | public enum SchemaType 13 | { 14 | /// Uses oneOf with null schema and null type to express the nullability of a property (valid JSON Schema draft v4). 15 | JsonSchema, 16 | 17 | /// Uses required to express the nullability of a property (not valid in JSON Schema draft v4). 18 | Swagger2, 19 | 20 | /// Uses null handling of Open API 3. 21 | OpenApi3 22 | } 23 | } -------------------------------------------------------------------------------- /src/NJsonSchema/Validation/FormatValidators/GuidFormatValidator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace NJsonSchema.Validation.FormatValidators 12 | { 13 | /// Validator for "Guid" format. 14 | public class GuidFormatValidator : IFormatValidator 15 | { 16 | /// Gets the format attribute's value. 17 | public string Format { get; } = JsonFormatStrings.Guid; 18 | 19 | /// Gets the kind of error produced by validator. 20 | public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.GuidExpected; 21 | 22 | /// Validates format of given value. 23 | /// String value. 24 | /// Type of token holding the value. 25 | /// True if value is correct for given format, False - if not. 26 | public bool IsValid(string value, JTokenType tokenType) 27 | { 28 | return Guid.TryParse(value, out Guid guid); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/NJsonSchema/Validation/FormatValidators/IFormatValidator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace NJsonSchema.Validation.FormatValidators 12 | { 13 | /// Provides a method to verify if value is of valid format. 14 | public interface IFormatValidator 15 | { 16 | /// Validates format of given value. 17 | /// String value. 18 | /// Type of token holding the value. 19 | /// True if value is correct for given format, False - if not. 20 | bool IsValid(string value, JTokenType tokenType); 21 | 22 | /// Gets the kind of error produced by validator. 23 | ValidationErrorKind ValidationErrorKind { get; } 24 | 25 | /// Gets the format attribute's value. 26 | string Format { get; } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/NJsonSchema/Validation/FormatValidators/IpV6FormatValidator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace NJsonSchema.Validation.FormatValidators 12 | { 13 | /// Validator for "IpV6" format. 14 | public class IpV6FormatValidator : IFormatValidator 15 | { 16 | /// Gets the format attribute's value. 17 | public string Format { get; } = JsonFormatStrings.IpV6; 18 | 19 | /// Gets the kind of error produced by validator. 20 | public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.IpV6Expected; 21 | 22 | /// Validates format of given value. 23 | /// String value. 24 | /// Type of token holding the value. 25 | /// True if value is correct for given format, False - if not. 26 | public bool IsValid(string value, JTokenType tokenType) 27 | { 28 | return Uri.CheckHostName(value) == UriHostNameType.IPv6; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/NJsonSchema/Validation/FormatValidators/TimeSpanFormatValidator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace NJsonSchema.Validation.FormatValidators 12 | { 13 | /// Validator for "TimeSpan" format. 14 | public class TimeSpanFormatValidator : IFormatValidator 15 | { 16 | /// Gets the format attribute's value. 17 | public string Format { get; } = JsonFormatStrings.TimeSpan; 18 | 19 | /// Gets the kind of error produced by validator. 20 | public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.TimeSpanExpected; 21 | 22 | /// Validates format of given value. 23 | /// String value. 24 | /// Type of token holding the value. 25 | /// True if value is correct for given format, False - if not. 26 | public bool IsValid(string value, JTokenType tokenType) 27 | { 28 | return tokenType == JTokenType.TimeSpan 29 | || TimeSpan.TryParse(value, out TimeSpan timeSpanResult); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/NJsonSchema/Validation/FormatValidators/UriFormatValidator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace NJsonSchema.Validation.FormatValidators 12 | { 13 | /// Validator for "Uri" format. 14 | public class UriFormatValidator : IFormatValidator 15 | { 16 | /// Gets the format attribute's value. 17 | public string Format { get; } = JsonFormatStrings.Uri; 18 | 19 | /// Gets the kind of error produced by validator. 20 | public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.UriExpected; 21 | 22 | /// Validates format of given value. 23 | /// String value. 24 | /// Type of token holding the value. 25 | /// True if value is correct for given format, False - if not. 26 | public bool IsValid(string value, JTokenType tokenType) 27 | { 28 | return tokenType == JTokenType.Uri || 29 | Uri.TryCreate(value, UriKind.Absolute, out Uri? _); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/NJsonSchema/Validation/FormatValidators/UuidFormatValidator.cs: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------- 2 | // 3 | // Copyright (c) Rico Suter. All rights reserved. 4 | // 5 | // https://github.com/RicoSuter/NJsonSchema/blob/master/LICENSE.md 6 | // Rico Suter, mail@rsuter.com 7 | //----------------------------------------------------------------------- 8 | 9 | using Newtonsoft.Json.Linq; 10 | 11 | namespace NJsonSchema.Validation.FormatValidators 12 | { 13 | /// Validator for "Uuid" format. 14 | public class UuidFormatValidator : IFormatValidator 15 | { 16 | /// Gets the format attribute's value. 17 | #pragma warning disable CS0618 // Type or member is obsolete 18 | public string Format { get; } = JsonFormatStrings.Uuid; 19 | #pragma warning restore CS0618 // Type or member is obsolete 20 | 21 | /// Gets the kind of error produced by validator. 22 | public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.UuidExpected; 23 | 24 | /// Validates format of given value. 25 | /// String value. 26 | /// Type of token holding the value. 27 | /// True if value is correct for given format, False - if not. 28 | public bool IsValid(string value, JTokenType tokenType) 29 | { 30 | return Guid.TryParse(value, out Guid guid); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/NJsonSchema/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | --------------------------------------------------------------------------------