From 3f4549ce67f837e040387ee45ec63b520115b813 Mon Sep 17 00:00:00 2001 From: Rico Suter Date: Mon, 20 May 2019 18:33:58 +0200 Subject: [PATCH] Refactor projects (v10) (#969) * Rename JsonSchema4 to JsonSchema * Rename JsonProperty to JsonSchemaProperty * Fix ns * Move FromType methods * Revert "Move FromType methods" This reverts commit ee3716afff5b59d1b019e1723f968671cd51b361. * Add readme to sln * Move generation classes to correct namespace --- README.md | 12 +- .../SchemaGenerationPerformanceTests.cs | 2 +- .../SerializationPerformance.cs | 8 +- .../AbstractSchemaTests.cs | 2 +- .../AdditionalPropertiesTests.cs | 2 +- .../AllOfTests.cs | 10 +- .../AnnotationsTests.cs | 2 +- .../ArrayTests.cs | 4 +- .../DefaultPropertyTests.cs | 6 +- .../DictionaryTests.cs | 4 +- .../EnumTests.cs | 18 +- .../GeneralGeneratorTests.cs | 140 +- .../InheritanceInterfaceTests.cs | 2 +- .../InheritanceTests.cs | 6 +- .../InterfaceTests.cs | 4 +- .../NullableEnumTests.cs | 2 +- .../ObjectPropertyRequiredTests.cs | 8 +- .../ReferencesTest.cs | 4 +- .../StringPropertyRequiredTests.cs | 8 +- .../UriTests.cs | 2 +- .../ValueGeneratorTests.cs | 4 +- .../CSharpGenerator.cs | 6 +- .../CSharpPropertyNameGenerator.cs | 4 +- .../CSharpTypeResolver.cs | 22 +- .../CSharpValueGenerator.cs | 6 +- .../Models/ClassTemplateModel.cs | 6 +- .../Models/EnumTemplateModel.cs | 6 +- .../Models/PropertyModel.cs | 4 +- .../DefaultGenerationTests.cs | 6 +- .../DefaultValueGeneratorTests.cs | 18 +- .../EnumGenerationTests.cs | 22 +- .../InheritanceSerializationTests.cs | 12 +- .../Samples/SampleTests.cs | 8 +- .../AbstractGenerationTests.cs | 6 +- .../ClassGenerationTests.cs | 34 +- .../ConstructorInterfaceTests.cs | 4 +- .../DateCodeGenerationTests.cs | 16 +- .../DateTimeCodeGenerationTests.cs | 14 +- .../DictionaryTests.cs | 8 +- .../ExtensionCodeTests.cs | 2 +- .../InheritanceTests.cs | 4 +- .../NullabilityTests.cs | 10 +- .../TypeScriptDictionaryTests.cs | 6 +- .../TypeScriptGeneratorTests.cs | 24 +- .../TypeScriptObjectTests.cs | 4 +- .../DataConversionGenerator.cs | 2 +- .../DataConversionParameters.cs | 2 +- .../Models/ClassTemplateModel.cs | 8 +- .../Models/EnumTemplateModel.cs | 6 +- .../Models/PropertyModel.cs | 4 +- .../TypeScriptGenerator.cs | 4 +- .../TypeScriptPropertyNameGenerator.cs | 4 +- .../TypeScriptTypeResolver.cs | 18 +- .../TypeScriptValueGenerator.cs | 4 +- .../DefaultEnumNameGenerator.cs | 4 +- .../DefaultTemplateFactory.cs | 2 +- .../GeneratorBase.cs | 10 +- .../IEnumNameGenerator.cs | 4 +- .../IPropertyNameGenerator.cs | 4 +- .../JsonSchemaGraphUtilities.cs | 10 +- .../Models/ClassTemplateModelBase.cs | 6 +- .../Models/PropertyModelBase.cs | 4 +- .../Models/TemplateModelBase.cs | 2 +- .../TypeResolverBase.cs | 24 +- .../ValueGeneratorBase.cs | 8 +- src/NJsonSchema.Demo.Performance/Program.cs | 2 +- src/NJsonSchema.Demo/Program.cs | 2 +- .../Conversion/ArrayTypeToSchemaTests.cs | 4 +- .../Conversion/SchemaReferenceTests.cs | 10 +- .../Conversion/TypeToSchemaTests.cs | 32 +- .../Generation/AbstractGenerationTests.cs | 4 +- .../Generation/AnnotationsGenerationTests.cs | 30 +- .../Generation/ArrayGenerationTests.cs | 4 +- .../Generation/AttributeGenerationTests.cs | 22 +- .../Generation/ContractResolverTests.cs | 8 +- .../DefaultTypeNameGeneratorTests.cs | 2 +- .../Generation/DictionaryTests.cs | 6 +- .../Generation/EnumGenerationTests.cs | 14 +- src/NJsonSchema.Tests/Generation/EnumTests.cs | 10 +- .../Generation/ExceptionTypeTests.cs | 2 +- .../ExcplicitInterfacePropertyTests.cs | 2 +- .../ExtensionDataGenerationTests.cs | 2 +- .../Generation/FieldGenerationTests.cs | 2 +- .../FlattenInheritanceHierarchyTests.cs | 10 +- .../Generation/GenericTests.cs | 4 +- .../Generation/IgnoredPropertyTests.cs | 6 +- .../Generation/InheritanceTests.cs | 20 +- .../Generation/InterfaceTests.cs | 2 +- .../Generation/JsonPropertyAttributeTests.cs | 4 +- .../JsonSchemaTypeAttributeTests.cs | 8 +- .../Generation/KnownTypeGenerationTests.cs | 4 +- .../Generation/NullPropertyTests.cs | 4 +- .../PrimitiveTypeGenerationTests.cs | 18 +- .../PropertyNamesGenerationTests.cs | 6 +- .../SampleJsonSchemaGeneratorTests.cs | 4 +- .../Generation/SchemaGenerationTests.cs | 18 +- .../Generation/SchemaProcessorTests.cs | 2 +- .../Generation/ShouldSerializeTests.cs | 2 +- .../Generation/TypeMapperTests.cs | 12 +- .../Generation/XmlObjectTests.cs | 18 +- ...ndIgnoreSerializerContractResolverTests.cs | 16 +- .../References/LocalReferencesTests.cs | 14 +- .../Schema/DataContractTests.cs | 12 +- .../JsonPathUtilitiesGetJsonPathTests.cs | 8 +- ...PathUtilitiesGetObjectFromJsonPathTests.cs | 8 +- .../Schema/JsonSchemaTests.cs | 54 +- .../DiscriminatorSerializationTests.cs | 16 +- .../Serialization/ExtensionDataTests.cs | 14 +- .../Validation/ArrayValidationTests.cs | 40 +- .../Validation/EnumValidationTests.cs | 10 +- .../Validation/FormatBase64Tests.cs | 14 +- .../Validation/FormatDateTests.cs | 6 +- .../Validation/FormatDateTimeTests.cs | 12 +- .../Validation/FormatEmailTests.cs | 4 +- .../Validation/FormatGuidTests.cs | 4 +- .../Validation/FormatHostnameTests.cs | 4 +- .../Validation/FormatIpV4Tests.cs | 4 +- .../Validation/FormatIpV6Tests.cs | 4 +- .../Validation/FormatTimeSpanTests.cs | 4 +- .../Validation/FormatTimeTests.cs | 12 +- .../Validation/FormatUriTests.cs | 4 +- .../Validation/InheritanceTests.cs | 52 +- .../Validation/LineInformationTest.cs | 4 +- .../Validation/NullPropertyTests.cs | 8 +- .../Validation/NumberTests.cs | 4 +- .../Validation/ObjectValidationTests.cs | 26 +- .../Validation/OneOfValidationTests.cs | 6 +- .../PatternPropertyValidationTests.cs | 12 +- .../Validation/SchemaTests.cs | 6 +- .../Validation/UniqueItemsTests.cs | 2 +- .../Validation/ValueTypeValidationTests.cs | 36 +- .../JsonAndYamlReferenceResolver.cs | 4 +- src/NJsonSchema.Yaml/JsonSchemaYaml.cs | 30 +- src/NJsonSchema.sln | 5 + src/NJsonSchema/DefaultTypeNameGenerator.cs | 4 +- .../DefaultSchemaNameGenerator.cs | 14 +- .../{ => Generation}/EnumHandling.cs | 44 +- .../{ => Generation}/ISchemaNameGenerator.cs | 2 +- .../Generation/JsonSchemaGenerator.cs | 146 +- .../{ => Generation}/JsonSchemaResolver.cs | 142 +- .../Generation/JsonTypeDescription.cs | 2 +- .../{ => Generation}/PropertyNameHandling.cs | 2 +- .../ReferenceTypeNullHandling.cs | 2 +- .../Generation/SampleJsonSchemaGenerator.cs | 30 +- .../Generation/SchemaProcessorContext.cs | 4 +- .../DiscriminatorSchemaProcessor.cs | 2 +- .../Generation/TypeMappers/ITypeMapper.cs | 2 +- .../TypeMappers/ObjectTypeMapper.cs | 10 +- .../TypeMappers/PrimitiveTypeMapper.cs | 6 +- src/NJsonSchema/ITypeNameGenerator.cs | 4 +- .../IgnoreEmptyCollectionsContractResolver.cs | 3 +- ...nameAndIgnoreSerializerContractResolver.cs | 8 +- .../Infrastructure/XmlObjectExtension.cs | 10 +- src/NJsonSchema/JsonExtensionObject.cs | 2 +- src/NJsonSchema/JsonReferenceResolver.cs | 18 +- ...4.Reference.cs => JsonSchema.Reference.cs} | 10 +- ...ization.cs => JsonSchema.Serialization.cs} | 824 ++++---- .../{JsonSchema4.cs => JsonSchema.cs} | 1746 ++++++++--------- src/NJsonSchema/JsonSchemaAppender.cs | 4 +- ...{JsonProperty.cs => JsonSchemaProperty.cs} | 182 +- src/NJsonSchema/JsonXmlObject.cs | 2 +- src/NJsonSchema/OpenApiDiscriminator.cs | 14 +- .../Validation/ChildSchemaValidationError.cs | 8 +- .../Validation/JsonSchemaValidator.cs | 50 +- .../Validation/MultiTypeValidationError.cs | 4 +- src/NJsonSchema/Validation/ValidationError.cs | 4 +- .../Visitors/JsonReferenceVisitorBase.cs | 30 +- .../Visitors/JsonSchemaVisitorBase.cs | 8 +- 168 files changed, 2375 insertions(+), 2359 deletions(-) rename src/NJsonSchema/{ => Generation}/DefaultSchemaNameGenerator.cs (76%) rename src/NJsonSchema/{ => Generation}/EnumHandling.cs (95%) rename src/NJsonSchema/{ => Generation}/ISchemaNameGenerator.cs (95%) rename src/NJsonSchema/{ => Generation}/JsonSchemaResolver.cs (87%) rename src/NJsonSchema/{ => Generation}/PropertyNameHandling.cs (97%) rename src/NJsonSchema/{ => Generation}/ReferenceTypeNullHandling.cs (96%) rename src/NJsonSchema/{JsonSchema4.Reference.cs => JsonSchema.Reference.cs} (95%) rename src/NJsonSchema/{JsonSchema4.Serialization.cs => JsonSchema.Serialization.cs} (82%) rename src/NJsonSchema/{JsonSchema4.cs => JsonSchema.cs} (84%) rename src/NJsonSchema/{JsonProperty.cs => JsonSchemaProperty.cs} (93%) diff --git a/README.md b/README.md index 5423f63f8..e295c0874 100644 --- a/README.md +++ b/README.md @@ -27,9 +27,9 @@ CI NuGet Feed: https://www.myget.org/gallery/njsonschema-ci **Features:** -- [Read existing JSON Schemas](https://github.com/RSuter/NJsonSchema/wiki/JsonSchema4) and [validate JSON data](https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaValidator) (`JsonSchema4.FromJsonAsync()`) -- [Generate JSON Schema from .NET type via reflection](https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaGenerator) (with support for many attributes/annotations) (`JsonSchema4.FromTypeAsync()`) -- [Generate JSON Schema from sample JSON data](https://github.com/RSuter/NJsonSchema/wiki/SampleJsonSchemaGenerator) (`JsonSchema4.FromSampleJson()`) +- [Read existing JSON Schemas](https://github.com/RSuter/NJsonSchema/wiki/JsonSchema) and [validate JSON data](https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaValidator) (`JsonSchema.FromJsonAsync()`) +- [Generate JSON Schema from .NET type via reflection](https://github.com/RSuter/NJsonSchema/wiki/JsonSchemaGenerator) (with support for many attributes/annotations) (`JsonSchema.FromTypeAsync()`) +- [Generate JSON Schema from sample JSON data](https://github.com/RSuter/NJsonSchema/wiki/SampleJsonSchemaGenerator) (`JsonSchema.FromSampleJson()`) - Support for schema references ($ref) (relative, URL and file) - Generate C# and TypeScript code from JSON Schema - Support for .NET Core (via PCL 259 / .NET Standard 1.0, also see [XML Documentation](https://github.com/NJsonSchema/NJsonSchema/wiki/XML-Documentation)) @@ -41,17 +41,17 @@ The project is developed and maintained by [Rico Suter](http://rsuter.com) and o ## NJsonSchema usage -The [JsonSchema4](https://github.com/NJsonSchema/NJsonSchema/wiki/JsonSchema4) class can be used as follows: +The [JsonSchema](https://github.com/NJsonSchema/NJsonSchema/wiki/JsonSchema) class can be used as follows: ```csharp -var schema = await JsonSchema4.FromTypeAsync(); +var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); var errors = schema.Validate("{...}"); foreach (var error in errors) Console.WriteLine(error.Path + ": " + error.Kind); -schema = await JsonSchema4.FromJsonAsync(schemaData); +schema = await JsonSchema.FromJsonAsync(schemaData); ``` The `Person` class: diff --git a/src/NJsonSchema.Benchmark/SchemaGenerationPerformanceTests.cs b/src/NJsonSchema.Benchmark/SchemaGenerationPerformanceTests.cs index 761bff0b2..d82982287 100644 --- a/src/NJsonSchema.Benchmark/SchemaGenerationPerformanceTests.cs +++ b/src/NJsonSchema.Benchmark/SchemaGenerationPerformanceTests.cs @@ -38,7 +38,7 @@ public void Setup(BenchmarkContext context) [CounterThroughputAssertion("Iterations", MustBe.GreaterThan, 100)] public void GenerateSchema() { - var schema = JsonSchema4.FromTypeAsync().GetAwaiter().GetResult(); + var schema = JsonSchema.FromTypeAsync().GetAwaiter().GetResult(); _counter.Increment(); } diff --git a/src/NJsonSchema.Benchmark/SerializationPerformance.cs b/src/NJsonSchema.Benchmark/SerializationPerformance.cs index 4608175c2..171e2244f 100644 --- a/src/NJsonSchema.Benchmark/SerializationPerformance.cs +++ b/src/NJsonSchema.Benchmark/SerializationPerformance.cs @@ -7,7 +7,7 @@ namespace NJsonSchema.Benchmark public class SerializationPerformance { private readonly string _json; - private readonly JsonSchema4 _schema; + private readonly JsonSchema _schema; public SerializationPerformance() { @@ -22,7 +22,7 @@ public SerializationPerformance() _json = reader.ReadToEnd(); } - _schema = JsonSchema4.FromJsonAsync(_json).Result; + _schema = JsonSchema.FromJsonAsync(_json).Result; } [Benchmark] @@ -32,9 +32,9 @@ public string ToJson() } [Benchmark] - public JsonSchema4 FromJson() + public JsonSchema FromJson() { - return JsonSchema4.FromJsonAsync(_json).Result; + return JsonSchema.FromJsonAsync(_json).Result; } } } diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AbstractSchemaTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AbstractSchemaTests.cs index f370acedb..2c15bd06d 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AbstractSchemaTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AbstractSchemaTests.cs @@ -15,7 +15,7 @@ public abstract class AbstractClass public async Task When_class_is_abstract_then_is_abstract_CSharp_keyword_is_generated() { /// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); /// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AdditionalPropertiesTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AdditionalPropertiesTests.cs index 0bb205a21..497d7e4b3 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AdditionalPropertiesTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AdditionalPropertiesTests.cs @@ -30,7 +30,7 @@ public async Task When_additionalProperties_schema_is_set_for_object_then_specia } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AllOfTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AllOfTests.cs index 604b94c3c..fe37d09de 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AllOfTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AllOfTests.cs @@ -43,7 +43,7 @@ public async Task When_allOf_has_two_schemas_then_referenced_schema_is_inherited } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); @@ -95,7 +95,7 @@ public async Task When_allOf_has_one_schema_then_it_is_inherited() } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); @@ -150,7 +150,7 @@ public async Task When_all_of_has_multiple_refs_then_the_properties_should_expan }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, Namespace = "ns" }; var generator = new CSharpGenerator(schema, settings); var output = generator.GenerateFile("Foo"); @@ -188,7 +188,7 @@ public async Task When_more_properties_are_defined_in_allOf_and_type_none_then_a }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); var code = generator.GenerateFile("Foo").Replace("\r\n", "\n"); @@ -231,7 +231,7 @@ public async Task When_allOf_schema_is_object_type_then_it_is_an_inherited_class }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); var code = generator.GenerateFile("Foo"); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AnnotationsTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AnnotationsTests.cs index 31469c7eb..706522ad8 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/AnnotationsTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/AnnotationsTests.cs @@ -23,7 +23,7 @@ public class MyRequiredTest public async Task When_array_property_is_not_nullable_then_it_does_not_have_a_setter() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ArrayTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ArrayTests.cs index 4360cb1c3..73a61f61c 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ArrayTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ArrayTests.cs @@ -18,7 +18,7 @@ public class ArrayTest public async Task When_array_property_is_required_then_array_instance_can_be_changed() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -45,7 +45,7 @@ public class ClassWithNullableArrayItems public async Task When_array_item_is_nullable_then_generated_CSharp_is_correct() { // Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs index a0da40d4b..447351dc6 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs @@ -16,7 +16,7 @@ public async Task When_property_has_interger_default_it_is_reflected_in_the_poco } }}"; - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, @@ -39,7 +39,7 @@ public async Task When_property_has_boolean_default_it_is_reflected_in_the_poco( } }}"; - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, @@ -62,7 +62,7 @@ public async Task When_property_has_boolean_default_and_default_value_generation } }}"; - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DictionaryTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DictionaryTests.cs index 917a20282..971e58618 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DictionaryTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DictionaryTests.cs @@ -25,7 +25,7 @@ public class EnumKeyDictionaryTest public async Task When_dictionary_key_is_enum_then_csharp_has_enum_key() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -41,7 +41,7 @@ public async Task When_dictionary_key_is_enum_then_csharp_has_enum_key() public async Task When_dictionary_property_is_required_then_dictionary_instance_can_be_changed() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/EnumTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/EnumTests.cs index 25cad9d51..1046d4b8d 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/EnumTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/EnumTests.cs @@ -26,7 +26,7 @@ public async Task When_enum_has_no_type_then_enum_is_generated() } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema); //// Act @@ -56,7 +56,7 @@ public async Task When_enum_has_no_type_then_enum_is_generated_with_flags() } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { EnforceFlagEnums = true }); //// Act @@ -109,7 +109,7 @@ public async Task When_enum_name_contains_colon_then_it_is_removed_and_next_word } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema); //// Act @@ -137,7 +137,7 @@ public enum MyStringEnum public async Task When_enum_list_uses_string_enums_then_ItemConverterType_is_set() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -152,7 +152,7 @@ public async Task When_enum_list_uses_string_enums_then_ItemConverterType_is_set public async Task When_enum_is_nullable_then_StringEnumConverter_is_set() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -175,7 +175,7 @@ public class SomeClass public async Task When_class_has_enum_array_property_then_enum_name_is_preserved() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); var json = schema.ToJson(); //// Act @@ -216,7 +216,7 @@ public async Task When_type_name_hint_has_generics_then_they_are_converted() } }"; /// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var settings = new CSharpGeneratorSettings(); var generator = new CSharpGenerator(schema, settings); @@ -250,7 +250,7 @@ public async Task When_enum_property_is_not_required_in_Swagger2_then_it_is_null } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { SchemaType = SchemaType.Swagger2 }); //// Act @@ -298,7 +298,7 @@ public async Task When_array_item_enum_is_not_referenced_then_type_name_hint_is_ } }"; /// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var settings = new CSharpGeneratorSettings(); var generator = new CSharpGenerator(schema, settings); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs index e865c5065..e2e57d0e7 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs @@ -29,7 +29,7 @@ public async Task When_type_is_array_and_items_and_item_is_not_defined_then_any_ 'emptySchema': { 'type': 'array' } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, Namespace = "ns", }; @@ -44,14 +44,14 @@ public async Task When_type_is_array_and_items_and_item_is_not_defined_then_any_ class CustomPropertyNameGenerator : IPropertyNameGenerator { - public string Generate(JsonProperty property) + public string Generate(JsonSchemaProperty property) { return "MyCustom" + ConversionUtilities.ConvertToUpperCamelCase(property.Name, true); } } class CustomTypeNameGenerator : ITypeNameGenerator { - public string Generate(JsonSchema4 schema, string typeNameHint, IEnumerable reservedTypeNames) + public string Generate(JsonSchema schema, string typeNameHint, IEnumerable reservedTypeNames) { return "MyCustomType" + ConversionUtilities.ConvertToUpperCamelCase(typeNameHint, true); } @@ -108,7 +108,7 @@ public class Address public async Task When_property_name_is_created_by_custom_fun_then_attribute_is_correct() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); var settings = new CSharpGeneratorSettings(); @@ -161,7 +161,7 @@ public async Task When_schema_contains_ref_to_definition_that_refs_another_defin } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco @@ -229,7 +229,7 @@ public async Task When_property_name_does_not_match_property_name_then_attribute public async Task When_property_is_timespan_than_csharp_timespan_is_used() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema); @@ -261,7 +261,7 @@ public async Task When_allOf_contains_one_schema_then_csharp_inheritance_is_gene public async Task When_enum_has_description_then_csharp_has_xml_comment() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.AllOf.First().ActualSchema.Properties["Gender"].Description = "EnumDesc."; var generator = new CSharpGenerator(schema); @@ -278,7 +278,7 @@ public async Task When_enum_has_description_then_csharp_has_xml_comment() public async Task When_class_has_description_then_csharp_has_xml_comment() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.ActualSchema.Description = "ClassDesc."; var generator = new CSharpGenerator(schema); @@ -295,7 +295,7 @@ public async Task When_class_has_description_then_csharp_has_xml_comment() public async Task When_property_has_description_then_csharp_has_xml_comment() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.ActualProperties["Class"].Description = "PropertyDesc."; var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -317,7 +317,7 @@ public class File public async Task Can_generate_type_from_string_property_with_byte_format() { // Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var generator = new CSharpGenerator(schema); // Act @@ -333,7 +333,7 @@ public async Task Can_generate_type_from_string_property_with_byte_format() public async Task Can_generate_type_from_string_property_with_base64_format() { // Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.Properties["Content"].Format = "base64"; var generator = new CSharpGenerator(schema); @@ -350,8 +350,8 @@ public async Task Can_generate_type_from_string_property_with_base64_format() public void When_name_contains_dash_then_it_is_converted_to_upper_case() { //// Arrange - var schema = new JsonSchema4(); - schema.Properties["foo-bar"] = new JsonProperty + var schema = new JsonSchema(); + schema.Properties["foo-bar"] = new JsonSchemaProperty { Type = JsonObjectType.String }; @@ -380,8 +380,8 @@ public void When_name_contains_dash_then_it_is_converted_to_upper_case() public void When_name_contains_unallowed_characters_then_they_are_converted_to_valid_csharp(string jsonPropertyName, string expectedCSharpName) { // Arrange - var schema = new JsonSchema4(); - schema.Properties[jsonPropertyName] = new JsonProperty + var schema = new JsonSchema(); + schema.Properties[jsonPropertyName] = new JsonSchemaProperty { Type = JsonObjectType.String }; @@ -402,7 +402,7 @@ public void When_name_contains_unallowed_characters_then_they_are_converted_to_v public void When_type_name_is_missing_then_anonymous_name_is_generated() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); var generator = new CSharpGenerator(schema); // Act @@ -416,7 +416,7 @@ public void When_type_name_is_missing_then_anonymous_name_is_generated() private static async Task CreateGeneratorAsync() { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); var settings = new CSharpGeneratorSettings(); settings.Namespace = "MyNamespace"; @@ -436,7 +436,7 @@ public async Task When_property_is_object_then_any_type_is_generated() //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal( @@ -449,7 +449,7 @@ public async Task When_property_is_object_then_any_type_is_generated() public async Task When_property_is_object_then_object_property_is_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act @@ -481,7 +481,7 @@ public class ClassWithDefaultEnumProperty public async Task When_enum_property_has_default_and_int_serialization_then_correct_csharp_code_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaJson = schema.ToJson(); //// Act @@ -502,7 +502,7 @@ public async Task When_enum_property_has_default_and_int_serialization_then_corr public async Task When_enum_property_has_default_and_string_serialization_then_correct_csharp_code_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.String }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.String }); var schemaJson = schema.ToJson(); //// Act @@ -545,7 +545,7 @@ public async Task When_enum_type_name_is_missing_then_default_value_is_still_cor } } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -573,7 +573,7 @@ public async Task When_property_has_same_name_as_class_then_it_is_renamed() } } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -605,7 +605,7 @@ public async Task When_patternProperties_is_set_with_string_value_type_then_corr } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -621,9 +621,9 @@ public async Task When_patternProperties_is_set_with_string_value_type_then_corr public void When_object_has_generic_name_then_it_is_transformed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["foo"] = new JsonProperty + schema.Properties["foo"] = new JsonSchemaProperty { Type = JsonObjectType.Number }; @@ -657,7 +657,7 @@ public partial class Person2 public async Task When_property_is_required_then_CSharp_code_is_correct() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaJson = schema.ToJson(); //// Act @@ -703,24 +703,24 @@ public async Task When_property_is_required_then_CSharp_code_is_correct() public void When_array_property_is_required_or_not_then_the_code_has_correct_initializer() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Properties = { - { "A", new JsonProperty + { "A", new JsonSchemaProperty { Type = JsonObjectType.Array, - Item = new JsonSchema4 + Item = new JsonSchema { Type = JsonObjectType.String }, IsRequired = true } }, - { "B", new JsonProperty + { "B", new JsonSchemaProperty { Type = JsonObjectType.Array, - Item = new JsonSchema4 + Item = new JsonSchema { Type = JsonObjectType.String }, @@ -749,24 +749,24 @@ public void When_array_property_is_required_or_not_then_the_code_has_correct_ini public void When_dictionary_property_is_required_or_not_then_the_code_has_correct_initializer() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Properties = { - { "A", new JsonProperty + { "A", new JsonSchemaProperty { Type = JsonObjectType.Object, - AdditionalPropertiesSchema = new JsonSchema4 + AdditionalPropertiesSchema = new JsonSchema { Type = JsonObjectType.String }, IsRequired = true } }, - { "B", new JsonProperty + { "B", new JsonSchemaProperty { Type = JsonObjectType.Object, - AdditionalPropertiesSchema = new JsonSchema4 + AdditionalPropertiesSchema = new JsonSchema { Type = JsonObjectType.String }, @@ -795,16 +795,16 @@ public void When_dictionary_property_is_required_or_not_then_the_code_has_correc public void When_object_property_is_required_or_not_then_the_code_has_correct_initializer() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Properties = { - { "A", new JsonProperty + { "A", new JsonSchemaProperty { Type = JsonObjectType.Object, Properties = { - {"A", new JsonProperty + {"A", new JsonSchemaProperty { Type = JsonObjectType.String } @@ -813,12 +813,12 @@ public void When_object_property_is_required_or_not_then_the_code_has_correct_in IsRequired = true } }, - { "B", new JsonProperty + { "B", new JsonSchemaProperty { Type = JsonObjectType.Object, Properties = { - {"A", new JsonProperty + {"A", new JsonSchemaProperty { Type = JsonObjectType.String } @@ -864,7 +864,7 @@ public async Task When_definition_is_named_Object_then_JObject_is_generated() } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -889,7 +889,7 @@ public class ObsClass public async Task When_property_is_ObservableCollection_then_generated_code_uses_the_same_class() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var settings = new CSharpGeneratorSettings { ArrayType = "ObservableCollection" }; var generator = new CSharpGenerator(schema, settings); @@ -908,7 +908,7 @@ public async Task When_enum_has_special_chars_then_they_should_be_converted() { //// Arrange var schemaJson = @"{ ""type"": ""string"", ""enum"": [""application/json"",""application/vnd.ms-excel""] }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var settings = new CSharpGeneratorSettings(); var generator = new CSharpGenerator(schema, settings); @@ -933,7 +933,7 @@ public async Task When_property_has_not_supported_characters_then_they_are_remov ""@odata.context"": { ""type"": ""string"" } } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var settings = new CSharpGeneratorSettings(); var generator = new CSharpGenerator(schema, settings); @@ -961,7 +961,7 @@ public async Task When_definition_contains_minimum_a_range_attribute_is_added_wi } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -991,7 +991,7 @@ public async Task When_definition_contains_maximum_a_range_attribute_is_added_wi } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1022,7 +1022,7 @@ public async Task When_definition_contains_both_minimum_and_maximum_a_range_attr } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1052,7 +1052,7 @@ public async Task When_definition_contains_maximum_a_range_attribute_is_not_adde } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1082,7 +1082,7 @@ public async Task When_definition_contains_min_length_a_string_length_attribute_ } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1112,7 +1112,7 @@ public async Task When_definition_contains_max_length_a_string_length_attribute_ } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1143,7 +1143,7 @@ public async Task When_definition_contains_both_min_and_max_length_a_string_leng } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1174,7 +1174,7 @@ public async Task When_definition_contains_both_min_length_a_string_length_attri } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1205,7 +1205,7 @@ public async Task When_definition_contains_both_min_items_and_max_items_a_min_le } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1236,7 +1236,7 @@ public async Task When_definition_contains_pattern_a_regular_expression_attribut } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1266,7 +1266,7 @@ public async Task When_definition_contains_pattern_but_type_is_not_string_a_regu } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1306,7 +1306,7 @@ public async Task When_definition_contains_restrictions_but_render_data_annotati } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1333,7 +1333,7 @@ public class MyByteTest public async Task When_property_is_byte_then_its_type_is_preserved() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act @@ -1356,7 +1356,7 @@ public class MyRequiredNullableTest public async Task When_nullable_property_is_required_then_it_is_not_nullable_in_generated_csharp_code() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act @@ -1383,7 +1383,7 @@ public async Task When_definition_contains_date_converter_should_be_added_for_da } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1424,7 +1424,7 @@ public async Task When_no_typeNameHint_is_available_then_title_is_used_as_class_ } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1485,7 +1485,7 @@ public async Task When_tuple_types_has_ints_then_it_is_generated_correctly(bool } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1527,7 +1527,7 @@ public async Task When_definition_contains_date_converter_should_be_added_for_da } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1559,7 +1559,7 @@ public async Task When_definition_contains_datetime_converter_should_not_be_adde } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1581,7 +1581,7 @@ public async Task When_definition_contains_datetime_converter_should_not_be_adde public async Task When_record_no_setter_in_class_and_constructor_provided() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync
(); + var schema = await JsonSchema.FromTypeAsync
(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { @@ -1625,7 +1625,7 @@ public class PersonAddress : PostAddress public async Task When_class_is_abstract_constructor_is_protected_for_record() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { @@ -1652,7 +1652,7 @@ public async Task When_class_is_abstract_constructor_is_protected_for_record() public async Task When_record_has_inheritance() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { @@ -1685,7 +1685,7 @@ public class ClassWithExtensionData public async Task When_schema_has_AdditionProperties_schema_then_JsonExtensionDataAttribute_is_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); var json = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -1708,7 +1708,7 @@ public void When_schema_has_negative_value_of_enum_it_is_generated_in_CSharp_and var generator = new CSharpGenerator(null, settings); //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Integer, Enumeration = diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceInterfaceTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceInterfaceTests.cs index 75b2b4782..1df1c78a6 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceInterfaceTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceInterfaceTests.cs @@ -45,7 +45,7 @@ public class Banana : Fruit, IBanana public async Task When_schema_has_base_schema_then_it_is_referenced() { //// Arrange - var json = await JsonSchema4.FromTypeAsync(); + var json = await JsonSchema.FromTypeAsync(); var data = json.ToJson(); var generator = new CSharpGenerator(json, new CSharpGeneratorSettings()); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceTests.cs index 8472a9e17..53a8c8e4e 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/InheritanceTests.cs @@ -28,7 +28,7 @@ public sealed class EmptyClassInheritingDictionary : Dictionary public async Task When_empty_class_inherits_from_dictionary_then_allOf_inheritance_still_works() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); @@ -73,7 +73,7 @@ public class ExceptionContainer public async Task When_class_with_discriminator_has_base_class_then_csharp_is_generated_correctly() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -123,7 +123,7 @@ public async Task When_property_references_any_schema_with_inheritance_then_prop } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); //// Act diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/InterfaceTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/InterfaceTests.cs index 751a5c0d7..3fba5a8b1 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/InterfaceTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/InterfaceTests.cs @@ -22,7 +22,7 @@ public class Person : IPerson public async Task When_interface_has_properties_then_properties_are_included_in_schema() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -42,7 +42,7 @@ public async Task When_interface_has_properties_then_properties_are_included_in_ public async Task When_class_implements_interface_then_properties_are_included_in_schema() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableEnumTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableEnumTests.cs index 9ef1a3d3f..9ade547f9 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableEnumTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableEnumTests.cs @@ -27,7 +27,7 @@ public async Task When_Swagger2_enum_property_is_not_required_then_it_is_nullabl } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { SchemaType = SchemaType.Swagger2, diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ObjectPropertyRequiredTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ObjectPropertyRequiredTests.cs index 8f415cf8e..cbd0c8664 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ObjectPropertyRequiredTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ObjectPropertyRequiredTests.cs @@ -18,7 +18,7 @@ private class ClassWithRequiredObject public async Task When_property_is_required_then_required_attribute_is_rendered_in_Swagger_mode() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 }); @@ -41,7 +41,7 @@ public async Task When_property_is_required_then_required_attribute_is_rendered_ public async Task When_property_is_required_then_required_attribute_is_rendered() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act @@ -65,7 +65,7 @@ private class ClassWithoutRequiredObject public async Task When_property_is_not_required_then_required_attribute_is_not_rendered_in_Swagger_mode() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 }); @@ -89,7 +89,7 @@ public async Task When_property_is_not_required_then_required_attribute_is_not_r public async Task When_property_is_not_required_then_required_attribute_is_not_rendered() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ReferencesTest.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ReferencesTest.cs index b92723519..21d3b1eaf 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ReferencesTest.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ReferencesTest.cs @@ -16,7 +16,7 @@ public async Task When_ref_is_definitions_no_types_are_duplicated() var path = GetTestDirectory() + "/References/E.json"; //// Act - var schema = await JsonSchema4.FromFileAsync(path); + var schema = await JsonSchema.FromFileAsync(path); var generator = new CSharpGenerator(schema); //// Act @@ -34,7 +34,7 @@ public async Task When_ref_is_file_no_types_are_duplicated() var path = GetTestDirectory() + "/References/A.json"; //// Act - var schema = await JsonSchema4.FromFileAsync(path); + var schema = await JsonSchema.FromFileAsync(path); var generator = new CSharpGenerator(schema); //// Act diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/StringPropertyRequiredTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/StringPropertyRequiredTests.cs index 909a44f8e..f7686ed60 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/StringPropertyRequiredTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/StringPropertyRequiredTests.cs @@ -20,7 +20,7 @@ private class ClassWithRequiredObject public async Task When_property_is_required_then_required_attribute_is_rendered_in_Swagger_mode() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); var schemaData = schema.ToJson(); //// Act @@ -46,7 +46,7 @@ public async Task When_property_is_required_then_required_attribute_is_rendered_ public async Task When_property_is_required_then_required_attribute_is_rendered() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act @@ -74,7 +74,7 @@ public class ClassWithoutRequiredObject public async Task When_property_is_not_required_then_required_attribute_is_not_rendered_in_Swagger_mode() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 }); @@ -97,7 +97,7 @@ public async Task When_property_is_not_required_then_required_attribute_is_not_r public async Task When_property_is_not_required_then_required_attribute_is_not_rendered() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/UriTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/UriTests.cs index d28a3314f..5bdfeb517 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/UriTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/UriTests.cs @@ -16,7 +16,7 @@ public class ClassWithUri public async Task When_property_is_uri_then_csharp_output_is_also_uri() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); var generator = new CSharpGenerator(schema); diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValueGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValueGeneratorTests.cs index 824f0b325..d2d8d8a89 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValueGeneratorTests.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ValueGeneratorTests.cs @@ -18,7 +18,7 @@ public class RangeClass public async Task When_schema_contains_range_then_code_is_correctly_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings @@ -51,7 +51,7 @@ public async Task When_property_is_integer_and_no_format_is_available_then_defau } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); /// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs index e968f87a3..885d85646 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs @@ -97,7 +97,7 @@ protected override string GenerateFile(IEnumerable artifactCollect /// The schema. /// The type name hint. /// The code. - protected override CodeArtifact GenerateType(JsonSchema4 schema, string typeNameHint) + protected override CodeArtifact GenerateType(JsonSchema schema, string typeNameHint) { var typeName = _resolver.GetOrGenerateTypeName(schema, typeNameHint); @@ -107,7 +107,7 @@ protected override CodeArtifact GenerateType(JsonSchema4 schema, string typeName return GenerateClass(schema, typeName); } - private CodeArtifact GenerateClass(JsonSchema4 schema, string typeName) + private CodeArtifact GenerateClass(JsonSchema schema, string typeName) { var model = new ClassTemplateModel(typeName, Settings, _resolver, schema, RootObject); @@ -130,7 +130,7 @@ private void RenamePropertyWithSameNameAsClass(string typeName, IEnumerableGenerates the property name for a given CSharp . + /// Generates the property name for a given CSharp . public class CSharpPropertyNameGenerator : IPropertyNameGenerator { /// Generates the property name. /// The property. /// The new name. - public virtual string Generate(JsonProperty property) + public virtual string Generate(JsonSchemaProperty property) { return ConversionUtilities.ConvertToUpperCamelCase(property.Name .Replace("\"", string.Empty) diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs index e3bedea37..094d1d9e6 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs @@ -24,7 +24,7 @@ public CSharpTypeResolver(CSharpGeneratorSettings settings) /// Initializes a new instance of the class. /// The generator settings. /// The exception type schema. - public CSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema4 exceptionSchema) + public CSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema exceptionSchema) : base(settings) { Settings = settings; @@ -32,7 +32,7 @@ public CSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema4 exceptio } /// Gets the exception schema. - public JsonSchema4 ExceptionSchema { get; } + public JsonSchema ExceptionSchema { get; } /// Gets the generator settings. public CSharpGeneratorSettings Settings { get; } @@ -42,7 +42,7 @@ public CSharpTypeResolver(CSharpGeneratorSettings settings, JsonSchema4 exceptio /// Specifies whether the given type usage is nullable. /// The type name hint to use when generating the type and the type name is missing. /// The type name. - public override string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint) + public override string Resolve(JsonSchema schema, bool isNullable, string typeNameHint) { return Resolve(schema, isNullable, typeNameHint, true); } @@ -53,7 +53,7 @@ public override string Resolve(JsonSchema4 schema, bool isNullable, string typeN /// The type name hint to use when generating the type and the type name is missing. /// Checks whether a named schema is already registered. /// The type name. - public string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint, bool checkForExistingSchema) + public string Resolve(JsonSchema schema, bool isNullable, string typeNameHint, bool checkForExistingSchema) { if (schema == null) throw new ArgumentNullException(nameof(schema)); @@ -108,7 +108,7 @@ public string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint, /// Checks whether the given schema should generate a type. /// The schema. /// True if the schema should generate a type. - protected override bool IsDefinitionTypeSchema(JsonSchema4 schema) + protected override bool IsDefinitionTypeSchema(JsonSchema schema) { if ((schema.IsDictionary && !Settings.InlineNamedDictionaries) || (schema.IsArray && !Settings.InlineNamedArrays) || @@ -120,7 +120,7 @@ protected override bool IsDefinitionTypeSchema(JsonSchema4 schema) return base.IsDefinitionTypeSchema(schema); } - private string ResolveString(JsonSchema4 schema, bool isNullable, string typeNameHint) + private string ResolveString(JsonSchema schema, bool isNullable, string typeNameHint) { if (schema.Format == JsonFormatStrings.Date) return isNullable && Settings.DateType?.ToLowerInvariant() != "string" ? Settings.DateType + "?" : Settings.DateType; @@ -155,7 +155,7 @@ private static string ResolveBoolean(bool isNullable) return isNullable ? "bool?" : "bool"; } - private string ResolveInteger(JsonSchema4 schema, bool isNullable, string typeNameHint) + private string ResolveInteger(JsonSchema schema, bool isNullable, string typeNameHint) { if (schema.Format == JsonFormatStrings.Byte) return isNullable ? "byte?" : "byte"; @@ -166,7 +166,7 @@ private string ResolveInteger(JsonSchema4 schema, bool isNullable, string typeNa return isNullable ? "int?" : "int"; } - private static string ResolveNumber(JsonSchema4 schema, bool isNullable) + private static string ResolveNumber(JsonSchema schema, bool isNullable) { if (schema.Format == JsonFormatStrings.Decimal) return isNullable ? "decimal?" : "decimal"; @@ -174,11 +174,11 @@ private static string ResolveNumber(JsonSchema4 schema, bool isNullable) return isNullable ? "double?" : "double"; } - private string ResolveArrayOrTuple(JsonSchema4 schema) + private string ResolveArrayOrTuple(JsonSchema schema) { if (schema.Item != null) { - var itemTypeNameHint = (schema as JsonProperty)?.Name; + var itemTypeNameHint = (schema as JsonSchemaProperty)?.Name; var itemType = Resolve(schema.Item, schema.Item.IsNullable(Settings.SchemaType), itemTypeNameHint); return string.Format(Settings.ArrayType + "<{0}>", itemType); } @@ -195,7 +195,7 @@ private string ResolveArrayOrTuple(JsonSchema4 schema) return Settings.ArrayType + ""; } - private string ResolveDictionary(JsonSchema4 schema) + private string ResolveDictionary(JsonSchema schema) { var valueType = ResolveDictionaryValueType(schema, "object"); var keyType = ResolveDictionaryKeyType(schema, "string"); diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs index f8858551d..93e4896be 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs @@ -38,7 +38,7 @@ public CSharpValueGenerator(CSharpGeneratorSettings settings) /// if set to true uses the default value from the schema if available. /// The type resolver. /// The code. - public override string GetDefaultValue(JsonSchema4 schema, bool allowsNull, string targetType, string typeNameHint, bool useSchemaDefault, TypeResolverBase typeResolver) + public override string GetDefaultValue(JsonSchema schema, bool allowsNull, string targetType, string typeNameHint, bool useSchemaDefault, TypeResolverBase typeResolver) { var value = base.GetDefaultValue(schema, allowsNull, targetType, typeNameHint, useSchemaDefault, typeResolver); if (value == null) @@ -52,7 +52,7 @@ public override string GetDefaultValue(JsonSchema4 schema, bool allowsNull, stri } } - var isOptional = (schema as JsonProperty)?.IsRequired == false; + var isOptional = (schema as JsonSchemaProperty)?.IsRequired == false; schema = schema.ActualSchema; if (schema != null && allowsNull == false && isOptional == false) @@ -115,7 +115,7 @@ public override string GetNumericValue(JsonObjectType type, object value, string /// The type name hint. /// The type resolver. /// The enum default value. - protected override string GetEnumDefaultValue(JsonSchema4 schema, JsonSchema4 actualSchema, string typeNameHint, TypeResolverBase typeResolver) + protected override string GetEnumDefaultValue(JsonSchema schema, JsonSchema actualSchema, string typeNameHint, TypeResolverBase typeResolver) { return _settings.Namespace + "." + base.GetEnumDefaultValue(schema, actualSchema, typeNameHint, typeResolver); } diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs index 9ec2c0e4a..fba2894fa 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs @@ -16,7 +16,7 @@ namespace NJsonSchema.CodeGeneration.CSharp.Models public class ClassTemplateModel : ClassTemplateModelBase { private readonly CSharpTypeResolver _resolver; - private readonly JsonSchema4 _schema; + private readonly JsonSchema _schema; private readonly CSharpGeneratorSettings _settings; /// Initializes a new instance of the class. @@ -26,7 +26,7 @@ public class ClassTemplateModel : ClassTemplateModelBase /// The schema. /// The root object. public ClassTemplateModel(string typeName, CSharpGeneratorSettings settings, - CSharpTypeResolver resolver, JsonSchema4 schema, object rootObject) + CSharpTypeResolver resolver, JsonSchema schema, object rootObject) : base(resolver, schema, rootObject) { _resolver = resolver; @@ -77,7 +77,7 @@ public ClassTemplateModel(string typeName, CSharpGeneratorSettings settings, public IEnumerable AllProperties { get; } /// Gets a value indicating whether the class has description. - public bool HasDescription => !(_schema is JsonProperty) && + public bool HasDescription => !(_schema is JsonSchemaProperty) && (!string.IsNullOrEmpty(_schema.Description) || !string.IsNullOrEmpty(_schema.ActualTypeSchema.Description)); diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs index dec13724c..db789f651 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs @@ -17,14 +17,14 @@ namespace NJsonSchema.CodeGeneration.CSharp.Models /// The CSharp enum template model. public class EnumTemplateModel : TemplateModelBase { - private readonly JsonSchema4 _schema; + private readonly JsonSchema _schema; private readonly CSharpGeneratorSettings _settings; /// Initializes a new instance of the class. /// Name of the type. /// The schema. /// The settings. - public EnumTemplateModel(string typeName, JsonSchema4 schema, CSharpGeneratorSettings settings) + public EnumTemplateModel(string typeName, JsonSchema schema, CSharpGeneratorSettings settings) { _schema = schema; _settings = settings; @@ -35,7 +35,7 @@ public EnumTemplateModel(string typeName, JsonSchema4 schema, CSharpGeneratorSet public string Name { get; } /// Gets a value indicating whether the enum has description. - public bool HasDescription => !(_schema is JsonProperty) && !string.IsNullOrEmpty(_schema.Description); + public bool HasDescription => !(_schema is JsonSchemaProperty) && !string.IsNullOrEmpty(_schema.Description); /// Gets the description. public string Description => _schema.Description; diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs index 7b765924d..1c4917336 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/PropertyModel.cs @@ -14,7 +14,7 @@ namespace NJsonSchema.CodeGeneration.CSharp.Models /// The CSharp property template model. public class PropertyModel : PropertyModelBase { - private readonly JsonProperty _property; + private readonly JsonSchemaProperty _property; private readonly CSharpGeneratorSettings _settings; private readonly CSharpTypeResolver _resolver; @@ -25,7 +25,7 @@ public class PropertyModel : PropertyModelBase /// The settings. public PropertyModel( ClassTemplateModel classTemplateModel, - JsonProperty property, + JsonSchemaProperty property, CSharpTypeResolver typeResolver, CSharpGeneratorSettings settings) : base(property, classTemplateModel, typeResolver, settings) diff --git a/src/NJsonSchema.CodeGeneration.Tests/DefaultGenerationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/DefaultGenerationTests.cs index 2877c93bb..f8652708e 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/DefaultGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/DefaultGenerationTests.cs @@ -20,7 +20,7 @@ public async Task When_property_has_default_attribute_then_default_is_in_schema( //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -33,7 +33,7 @@ public async Task When_property_has_default_attribute_then_default_is_in_schema( public async Task When_property_has_default_attribute_then_default_value_is_set_in_generated_INPC_CSharp_code() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -51,7 +51,7 @@ public async Task When_property_has_default_attribute_then_default_value_is_set_ public async Task When_property_has_default_attribute_then_default_value_is_set_in_generated_Poco_CSharp_code() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); diff --git a/src/NJsonSchema.CodeGeneration.Tests/DefaultValueGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.Tests/DefaultValueGeneratorTests.cs index b706199bf..ceaf3f07e 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/DefaultValueGeneratorTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/DefaultValueGeneratorTests.cs @@ -28,7 +28,7 @@ public void When_schema_has_default_value_of_int_it_is_generated_in_CSharp_and_T //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Integer, Default = (int)6 @@ -50,7 +50,7 @@ public void When_schema_has_default_value_of_long_it_is_generated_in_CSharp_and_ //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Integer, Format = JsonFormatStrings.Long, @@ -73,7 +73,7 @@ public void When_schema_has_default_value_of_double_it_is_generated_in_CSharp_an //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Number, Format = JsonFormatStrings.Double, @@ -96,7 +96,7 @@ public void When_schema_has_default_value_of_double_without_format_it_is_generat //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Number, Default = 1234.567F @@ -118,7 +118,7 @@ public void When_schema_has_default_value_of_float_it_is_generated_in_CSharp_and //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Number, Format = JsonFormatStrings.Float, @@ -141,7 +141,7 @@ public void When_schema_has_default_value_of_bool_it_is_generated_in_CSharp_and_ //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.Boolean, Default = true @@ -163,7 +163,7 @@ public void When_schema_has_default_value_of_string_it_is_generated_in_CSharp_an //// Arrange //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.String, Default = "test\\test\"test\r\ntest" @@ -181,7 +181,7 @@ public void When_schema_has_default_value_of_string_it_is_generated_in_CSharp_an public class MyEnumNameGenerator : IEnumNameGenerator { - public string Generate(int index, string name, object value, JsonSchema4 schema) + public string Generate(int index, string name, object value, JsonSchema schema) { return name.ToLowerInvariant(); } @@ -196,7 +196,7 @@ public void When_schema_has_default_value_of_enum_it_is_generated_in_CSharp_and_ var csharpTypeResolver = new CSharpTypeResolver(csharpSettings); //// Act - var schema = new JsonSchema4() + var schema = new JsonSchema() { Type = JsonObjectType.String, Enumeration = diff --git a/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs index 34647d378..924faeeab 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs @@ -36,7 +36,7 @@ public enum Bar public async Task When_string_and_integer_enum_used_then_two_enums_are_generated_in_typescript() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -54,7 +54,7 @@ public async Task When_string_and_integer_enum_used_then_two_enums_are_generated public async Task When_export_types_is_true_add_export_before_enum_in_typescript() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); var data = schema.ToJson(); TypeScriptGeneratorSettings typeScriptGeneratorSettings = new TypeScriptGeneratorSettings() @@ -74,7 +74,7 @@ public async Task When_export_types_is_true_add_export_before_enum_in_typescript public async Task When_add_export_keyword_is_false_dont_add_export_before_enum_in_typescript() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); var data = schema.ToJson(); TypeScriptGeneratorSettings typeScriptGeneratorSettings = new TypeScriptGeneratorSettings() @@ -94,7 +94,7 @@ public async Task When_add_export_keyword_is_false_dont_add_export_before_enum_i public async Task When_string_and_integer_enum_used_then_one_enum_is_generated_in_CSharp() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -118,7 +118,7 @@ public async Task When_string_and_integer_enum_used_then_one_enum_is_generated_i public async Task When_byte_enum_is_generated_then_no_exception_occurs() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -148,7 +148,7 @@ public enum ByteBar : byte public async Task When_enum_has_string_value_then_CS_code_has_EnumMember_attribute() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act @@ -166,7 +166,7 @@ public async Task When_enum_has_string_value_then_CS_code_has_EnumMember_attribu public async Task When_enum_has_string_value_then_TS_code_has_string_value() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act @@ -198,7 +198,7 @@ public enum StringEnum public async Task When_enum_has_integer_value_then_CS_code_has_EnumMember_attribute() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act @@ -216,7 +216,7 @@ public async Task When_enum_has_integer_value_then_CS_code_has_EnumMember_attrib public async Task When_enum_has_integer_value_then_TS_code_has_string_value() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act @@ -266,7 +266,7 @@ public async Task When_enum_has_no_names_and_string_value_starts_with_number_the } } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaData); + var schema = await JsonSchema.FromJsonAsync(schemaData); //// Act var generator = new CSharpGenerator(schema); @@ -305,7 +305,7 @@ public async Task When_property_is_nullable_and_enum_allows_null_then_no_excepti       }    } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); diff --git a/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs index 048488431..e98b4980f 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs @@ -98,7 +98,7 @@ public async Task When_JsonInheritanceConverter_is_used_then_inheritance_is_corr var json = JsonConvert.SerializeObject(container, Formatting.Indented); var deserializedContainer = JsonConvert.DeserializeObject(json); - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaJson = schema.ToJson(); var errors = schema.Validate(json); @@ -204,7 +204,7 @@ public void JsonInheritanceConverter_is_thread_safe() public async Task When_JsonInheritanceConverter_is_set_then_discriminator_field_is_set() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var baseSchema = schema.Properties["Animal"].ActualTypeSchema.ActualSchema; @@ -223,7 +223,7 @@ public async Task When_JsonInheritanceConverter_is_set_then_discriminator_field_ public async Task When_JsonInheritanceConverter_is_set_then_discriminator_mappings_are_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act @@ -240,7 +240,7 @@ public async Task When_JsonInheritanceConverter_is_set_then_discriminator_mappin public async Task When_schema_contains_discriminator_and_inheritance_hierarchy_then_CSharp_is_correctly_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); @@ -256,7 +256,7 @@ public async Task When_schema_contains_discriminator_and_inheritance_hierarchy_t public async Task When_schema_contains_discriminator_and_inheritance_hierarchy_then_TypeScript_is_correctly_generated() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act @@ -285,7 +285,7 @@ public async Task When_schema_contains_discriminator_and_inheritance_hierarchy_t public async Task Subtypes_are_serialized_with_correct_discriminator() { //// Arrange - var json = await JsonSchema4.FromJsonAsync(@"{""title"":""foo"",""type"":""object"",""discriminator"":""discriminator"",""properties"":{""discriminator"":{""type"":""string""}},""definitions"":{""bar"":{""type"":""object"",""allOf"":[{""$ref"":""#""}]}}}"); + var json = await JsonSchema.FromJsonAsync(@"{""title"":""foo"",""type"":""object"",""discriminator"":""discriminator"",""properties"":{""discriminator"":{""type"":""string""}},""definitions"":{""bar"":{""type"":""object"",""allOf"":[{""$ref"":""#""}]}}}"); var data = json.ToJson(); var generator = new CSharpGenerator(json, new CSharpGeneratorSettings() { ClassStyle = CSharpClassStyle.Poco, Namespace = "foo" }); diff --git a/src/NJsonSchema.CodeGeneration.Tests/Samples/SampleTests.cs b/src/NJsonSchema.CodeGeneration.Tests/Samples/SampleTests.cs index de276498d..ddc17bdd1 100644 --- a/src/NJsonSchema.CodeGeneration.Tests/Samples/SampleTests.cs +++ b/src/NJsonSchema.CodeGeneration.Tests/Samples/SampleTests.cs @@ -53,7 +53,7 @@ public class Company [Fact] public async Task Demo() { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaJsonData = schema.ToJson(); var errors = schema.Validate("{}"); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Class, TypeScriptVersion = 2.0m }); @@ -63,7 +63,7 @@ public async Task Demo() [Fact] public async Task Demo2() { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaJsonData = schema.ToJson(); var errors = schema.Validate("{}"); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Interface, TypeScriptVersion = 2.0m }); @@ -89,7 +89,7 @@ public async Task When_JSON_contains_DateTime_is_available_then_string_validator } } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var dataJson = @"{ ""SimpleDate"":""2012-05-18T00:00:00Z"", @@ -121,7 +121,7 @@ public async Task When_JSON_contains_DateTime_is_available_then_JObject_validato } } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var data = JObject.Parse(@"{ ""SimpleDate"":""2012-05-18T00:00:00Z"", diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/AbstractGenerationTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/AbstractGenerationTests.cs index 14b309c80..9d5db0d20 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/AbstractGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/AbstractGenerationTests.cs @@ -18,7 +18,7 @@ public abstract class AbstractClass : BaseClass public async Task When_class_is_abstract_then_is_abstract_TypeScript_keyword_is_generated() { /// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Act @@ -43,7 +43,7 @@ public class ContainerClass public async Task When_property_is_required_and_abstract_then_it_is_not_instantiated() { /// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Act @@ -72,7 +72,7 @@ public class SuperClass : AbstractClass public async Task When_abstract_class_is_in_inheritance_hierarchy_then_it_is_newer_instantiated() { /// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); /// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeScriptVersion = 2.0m }); diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ClassGenerationTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ClassGenerationTests.cs index 206d21d2d..6fc748ef0 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ClassGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ClassGenerationTests.cs @@ -81,7 +81,7 @@ public async Task When_generating_TypeScript_knockout_classes_then_output_is_cor private static async Task PrepareAsync(TypeScriptGeneratorSettings settings) { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -94,24 +94,24 @@ private static async Task PrepareAsync(TypeScriptGeneratorSettings setti public void When_array_property_is_required_or_not_then_the_code_has_correct_initializer() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Properties = { - { "A", new JsonProperty + { "A", new JsonSchemaProperty { Type = JsonObjectType.Array, - Item = new JsonSchema4 + Item = new JsonSchema { Type = JsonObjectType.String }, IsRequired = true } }, - { "B", new JsonProperty + { "B", new JsonSchemaProperty { Type = JsonObjectType.Array, - Item = new JsonSchema4 + Item = new JsonSchema { Type = JsonObjectType.String }, @@ -140,24 +140,24 @@ public void When_array_property_is_required_or_not_then_the_code_has_correct_ini public void When_dictionary_property_is_required_or_not_then_the_code_has_correct_initializer() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Properties = { - { "A", new JsonProperty + { "A", new JsonSchemaProperty { Type = JsonObjectType.Object, - AdditionalPropertiesSchema = new JsonSchema4 + AdditionalPropertiesSchema = new JsonSchema { Type = JsonObjectType.String }, IsRequired = true } }, - { "B", new JsonProperty + { "B", new JsonSchemaProperty { Type = JsonObjectType.Object, - AdditionalPropertiesSchema = new JsonSchema4 + AdditionalPropertiesSchema = new JsonSchema { Type = JsonObjectType.String }, @@ -186,16 +186,16 @@ public void When_dictionary_property_is_required_or_not_then_the_code_has_correc public void When_object_property_is_required_or_not_then_the_code_has_correct_initializer() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Properties = { - { "A", new JsonProperty + { "A", new JsonSchemaProperty { Type = JsonObjectType.Object, Properties = { - {"A", new JsonProperty + {"A", new JsonSchemaProperty { Type = JsonObjectType.String } @@ -204,12 +204,12 @@ public void When_object_property_is_required_or_not_then_the_code_has_correct_in IsRequired = true } }, - { "B", new JsonProperty + { "B", new JsonSchemaProperty { Type = JsonObjectType.Object, Properties = { - {"A", new JsonProperty + {"A", new JsonSchemaProperty { Type = JsonObjectType.String } @@ -322,7 +322,7 @@ public async Task When_Knockout_class_is_generated_then_initializers_are_correct public async Task When_GenerateConstructorInterface_is_disabled_then_data_is_not_checked_and_default_initialization_is_always_exectued() { // Assert - var schema = JsonSchema4.FromTypeAsync( + var schema = JsonSchema.FromTypeAsync( typeof(MyDerivedClass), new JsonSchemaGeneratorSettings { diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ConstructorInterfaceTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ConstructorInterfaceTests.cs index eecbae8e0..ce9f0479b 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ConstructorInterfaceTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ConstructorInterfaceTests.cs @@ -54,7 +54,7 @@ public class Skill public async Task When_constructor_interface_and_conversion_code_is_generated_then_it_is_correct() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); var json = schema.ToJson(); //// Act @@ -109,7 +109,7 @@ public async Task When_array_of_string_dictionary_is_used_with_ConvertConstructo } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateCodeGenerationTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateCodeGenerationTests.cs index 50af1f5e1..025266d6f 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateCodeGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateCodeGenerationTests.cs @@ -20,7 +20,7 @@ public class DateCodeGenerationTests public async Task When_date_handling_is_string_then_string_property_is_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -40,7 +40,7 @@ public async Task When_date_handling_is_string_then_string_property_is_generated public async Task When_date_handling_is_moment_then_moment_property_is_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -60,7 +60,7 @@ public async Task When_date_handling_is_moment_then_moment_property_is_generated public async Task When_date_handling_is_moment_then_duration_property_is_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -80,7 +80,7 @@ public async Task When_date_handling_is_moment_then_duration_property_is_generat public async Task When_date_handling_is_date_then_date_property_is_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -101,7 +101,7 @@ public async Task When_date_handling_is_date_then_date_property_is_generated_in_ public async Task When_date_handling_is_offset_moment_then_date_property_is_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -121,7 +121,7 @@ public async Task When_date_handling_is_offset_moment_then_date_property_is_gene public async Task When_date_handling_is_date_then_date_property_is_generated_in_interface() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -139,7 +139,7 @@ public async Task When_date_handling_is_date_then_date_property_is_generated_in_ public async Task When_date_handling_is_moment_then_moment_property_is_generated_in_interface() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -158,7 +158,7 @@ public async Task When_date_handling_is_moment_then_moment_property_is_generated public async Task When_date_handling_is_string_then_string_property_is_generated_in_interface() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync(Json); + var schema = await JsonSchema.FromJsonAsync(Json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateTimeCodeGenerationTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateTimeCodeGenerationTests.cs index ce61d04d8..dbe7633b5 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateTimeCodeGenerationTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DateTimeCodeGenerationTests.cs @@ -16,7 +16,7 @@ public class ClassWithDateTimeProperty public async Task When_date_handling_is_string_then_string_property_are_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -36,7 +36,7 @@ public async Task When_date_handling_is_string_then_string_property_are_generate public async Task When_date_handling_is_moment_then_moment_property_are_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -56,7 +56,7 @@ public async Task When_date_handling_is_moment_then_moment_property_are_generate public async Task When_date_handling_is_offset_moment_then_moment_property_are_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -76,7 +76,7 @@ public async Task When_date_handling_is_offset_moment_then_moment_property_are_g public async Task When_date_handling_is_date_then_date_property_are_generated_in_class() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -96,7 +96,7 @@ public async Task When_date_handling_is_date_then_date_property_are_generated_in public async Task When_date_handling_is_date_then_date_property_are_generated_in_interface() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -114,7 +114,7 @@ public async Task When_date_handling_is_date_then_date_property_are_generated_in public async Task When_date_handling_is_moment_then_moment_property_are_generated_in_interface() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -133,7 +133,7 @@ public async Task When_date_handling_is_moment_then_moment_property_are_generate public async Task When_date_handling_is_string_then_string_property_are_generated_in_interface() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DictionaryTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DictionaryTests.cs index ed527e171..da7a3aaf4 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DictionaryTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/DictionaryTests.cs @@ -122,7 +122,7 @@ public async Task When_property_is_dto_dictionary_then_assignment_may_create_new } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var codeGenerator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -148,7 +148,7 @@ public async Task When_property_is_object_and_not_dictionary_it_should_be_assign } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var codeGenerator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -183,7 +183,7 @@ public async Task When_property_is_string_dictionary_then_assignment_is_correct( } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var codeGenerator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -215,7 +215,7 @@ public class DisplayValueDictionary : Dictionary public async Task When_property_uses_custom_dictionary_class_then_class_is_generated(bool inlineNamedDictionaries, bool convertConstructorInterfaceData) { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs index b255e0cf8..ca1de76d3 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs @@ -96,7 +96,7 @@ public class Bar public async Task When_classes_have_extension_code_then_class_body_is_copied() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs index 25e85d6f6..74bd70349 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs @@ -30,7 +30,7 @@ public sealed class EmptyClassInheritingDictionary : Dictionary public async Task When_empty_class_inherits_from_dictionary_then_allOf_inheritance_still_works(bool inlineNamedDictionaries, bool convertConstructorInterfaceData) { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings @@ -97,7 +97,7 @@ public class ExceptionContainer public async Task When_class_with_discriminator_has_base_class_then_csharp_is_generated_correctly() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeScriptVersion = 2.0m }); diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NullabilityTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NullabilityTests.cs index 960668a61..b75f0ba3f 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NullabilityTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NullabilityTests.cs @@ -12,7 +12,7 @@ public class NullabilityTests [Fact] public async Task Strict_nullability_in_TypeScript2() { - var schema = await JsonSchema4.FromTypeAsync( + var schema = await JsonSchema.FromTypeAsync( new JsonSchemaGeneratorSettings { DefaultReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull @@ -37,7 +37,7 @@ public async Task Strict_nullability_in_TypeScript2() public async Task When_a_complex_property_is_not_required_and_not_nullable_then_default_is_undefined() { // Arrange - var schema = await JsonSchema4.FromJsonAsync(@"{ + var schema = await JsonSchema.FromJsonAsync(@"{ ""type"": ""object"", ""properties"": { ""parent"": { @@ -78,7 +78,7 @@ public async Task When_a_complex_property_is_not_required_and_not_nullable_then_ public async Task When_a_complex_property_is_required_and_not_nullable_then_default_is_new_instance() { // Arrange - var schema = await JsonSchema4.FromJsonAsync(@"{ + var schema = await JsonSchema.FromJsonAsync(@"{ ""type"": ""object"", ""properties"": { ""parent"": { @@ -120,7 +120,7 @@ public async Task When_a_complex_property_is_required_and_not_nullable_then_defa public async Task When_a_complex_property_is_nullable_then_default_is_null() { // Arrange - var schema = await JsonSchema4.FromJsonAsync(@"{ + var schema = await JsonSchema.FromJsonAsync(@"{ ""type"": ""object"", ""properties"": { ""parent"": { @@ -173,7 +173,7 @@ public class ClassWithNullableArrayItems public async Task When_array_item_is_nullable_then_generated_TypeScript_is_correct() { // Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptDictionaryTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptDictionaryTests.cs index 491c8d560..f0f1c5cb5 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptDictionaryTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptDictionaryTests.cs @@ -26,7 +26,7 @@ public class EnumKeyDictionaryTest public async Task When_dictionary_key_is_enum_then_typescript_has_string_key() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -46,7 +46,7 @@ public async Task When_dictionary_key_is_enum_then_typescript_has_string_key() public async Task When_dictionary_key_is_enum_then_typescript_has_enum_key_ts_2_1() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -76,7 +76,7 @@ public class EnumValueDictionaryTest public async Task When_dictionary_value_is_enum_then_typescript_has_enum_value() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptGeneratorTests.cs index 650d819a8..ab8343cd0 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptGeneratorTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptGeneratorTests.cs @@ -33,7 +33,7 @@ public async Task When_more_properties_are_defined_in_allOf_and_type_none_then_a }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Class, @@ -75,7 +75,7 @@ public async Task When_allOf_schema_is_object_type_then_it_is_an_inherited_class }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Class }); var code = generator.GenerateFile("Foo"); @@ -127,7 +127,7 @@ public async Task When_allOf_contains_one_schema_then_csharp_inheritance_is_gene public async Task When_enum_has_description_then_typescript_has_comment() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.AllOf.First().ActualSchema.Properties["Gender"].Description = "EnumDesc."; var generator = new TypeScriptGenerator(schema); @@ -142,7 +142,7 @@ public async Task When_enum_has_description_then_typescript_has_comment() public async Task When_class_has_description_then_typescript_has_comment() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.Description = "ClassDesc."; var generator = new TypeScriptGenerator(schema); @@ -157,7 +157,7 @@ public async Task When_class_has_description_then_typescript_has_comment() public async Task When_property_has_description_then_csharp_has_xml_comment() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); schema.ActualProperties["Class"].Description = "PropertyDesc."; var json = schema.ToJson(); @@ -174,7 +174,7 @@ public async Task When_property_has_description_then_csharp_has_xml_comment() public async Task When_property_is_readonly_then_ts_property_is_also_readonly() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Interface, @@ -192,8 +192,8 @@ public async Task When_property_is_readonly_then_ts_property_is_also_readonly() public void When_name_contains_dash_then_it_is_converted_to_upper_case() { //// Arrange - var schema = new JsonSchema4(); - schema.Properties["foo-bar"] = new JsonProperty + var schema = new JsonSchema(); + schema.Properties["foo-bar"] = new JsonSchemaProperty { Type = JsonObjectType.String }; @@ -211,7 +211,7 @@ public void When_name_contains_dash_then_it_is_converted_to_upper_case() public void When_type_name_is_missing_then_anonymous_name_is_generated() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); var generator = new TypeScriptGenerator(schema); @@ -224,7 +224,7 @@ public void When_type_name_is_missing_then_anonymous_name_is_generated() private static async Task CreateGeneratorAsync() { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { @@ -253,7 +253,7 @@ public async Task When_patternProperties_is_set_with_string_value_type_then_corr } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Class }); @@ -344,7 +344,7 @@ public async Task When_default_is_generated_then_no_liquid_error_is_in_output() } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Class }); diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptObjectTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptObjectTests.cs index fc6f77a01..8b382428a 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptObjectTests.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/TypeScriptObjectTests.cs @@ -16,7 +16,7 @@ public class ObjectTest public async Task When_property_is_object_then_jsonProperty_has_no_reference_and_is_any() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -40,7 +40,7 @@ public class DictionaryObjectTest public async Task When_dictionary_value_is_object_then_typescript_uses_any() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs index 04ee7455a..2ba9e15f5 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs @@ -145,7 +145,7 @@ private static bool IsDate(string format, TypeScriptDateTimeType type) return false; } - private static bool IsNewableObject(JsonSchema4 schema, DataConversionParameters parameters) + private static bool IsNewableObject(JsonSchema schema, DataConversionParameters parameters) { if (schema.ActualTypeSchema.IsEnumeration) return false; diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionParameters.cs b/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionParameters.cs index a028e2687..705845d8b 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionParameters.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionParameters.cs @@ -18,7 +18,7 @@ public class DataConversionParameters public string Value { get; set; } /// Gets the schema. - public JsonSchema4 Schema { get; set; } + public JsonSchema Schema { get; set; } /// Gets a value indicating whether the property is nullable. public bool IsPropertyNullable { get; set; } diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs b/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs index 8bd9a44b1..9645048c2 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs @@ -16,7 +16,7 @@ namespace NJsonSchema.CodeGeneration.TypeScript.Models public class ClassTemplateModel : ClassTemplateModelBase { private readonly TypeScriptGeneratorSettings _settings; - private readonly JsonSchema4 _schema; + private readonly JsonSchema _schema; private readonly TypeScriptTypeResolver _resolver; /// Initializes a new instance of the class. @@ -28,7 +28,7 @@ public class ClassTemplateModel : ClassTemplateModelBase /// The root object. public ClassTemplateModel(string typeName, string discriminatorName, TypeScriptGeneratorSettings settings, TypeScriptTypeResolver resolver, - JsonSchema4 schema, object rootObject) + JsonSchema schema, object rootObject) : base(resolver, schema, rootObject) { _settings = settings; @@ -60,7 +60,7 @@ public ClassTemplateModel(string typeName, string discriminatorName, public string BaseDiscriminator => _schema.ResponsibleDiscriminatorObject?.PropertyName; /// Gets a value indicating whether the class has description. - public bool HasDescription => !(_schema is JsonProperty) && + public bool HasDescription => !(_schema is JsonSchemaProperty) && (!string.IsNullOrEmpty(_schema.Description) || !string.IsNullOrEmpty(_schema.ActualTypeSchema.Description)); @@ -145,6 +145,6 @@ public string IndexerPropertyValueType public bool ExportTypes => _settings.ExportTypes; /// Gets the inherited schema. - private JsonSchema4 InheritedSchema => _schema.InheritedSchema?.ActualSchema; + private JsonSchema InheritedSchema => _schema.InheritedSchema?.ActualSchema; } } \ No newline at end of file diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/Models/EnumTemplateModel.cs b/src/NJsonSchema.CodeGeneration.TypeScript/Models/EnumTemplateModel.cs index f7ca10752..236a9e79c 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/Models/EnumTemplateModel.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/Models/EnumTemplateModel.cs @@ -15,14 +15,14 @@ namespace NJsonSchema.CodeGeneration.TypeScript.Models /// The TypeScript enum template model. public class EnumTemplateModel { - private readonly JsonSchema4 _schema; + private readonly JsonSchema _schema; private readonly TypeScriptGeneratorSettings _settings; /// Initializes a new instance of the class. /// Name of the type. /// The schema. /// The settings. - public EnumTemplateModel(string typeName, JsonSchema4 schema, TypeScriptGeneratorSettings settings) + public EnumTemplateModel(string typeName, JsonSchema schema, TypeScriptGeneratorSettings settings) { _schema = schema; _settings = settings; @@ -33,7 +33,7 @@ public EnumTemplateModel(string typeName, JsonSchema4 schema, TypeScriptGenerato public string Name { get; } /// Gets a value indicating whether the enum has description. - public bool HasDescription => !(_schema is JsonProperty) && !string.IsNullOrEmpty(_schema.Description); + public bool HasDescription => !(_schema is JsonSchemaProperty) && !string.IsNullOrEmpty(_schema.Description); /// Gets the description. public string Description => ConversionUtilities.RemoveLineBreaks(_schema.Description); diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/Models/PropertyModel.cs b/src/NJsonSchema.CodeGeneration.TypeScript/Models/PropertyModel.cs index c54435fcf..7cf0732c4 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/Models/PropertyModel.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/Models/PropertyModel.cs @@ -19,7 +19,7 @@ public class PropertyModel : PropertyModelBase private readonly string _parentTypeName; private readonly TypeScriptGeneratorSettings _settings; - private readonly JsonProperty _property; + private readonly JsonSchemaProperty _property; private readonly TypeScriptTypeResolver _resolver; /// Initializes a new instance of the class. @@ -30,7 +30,7 @@ public class PropertyModel : PropertyModelBase /// The settings. public PropertyModel( ClassTemplateModel classTemplateModel, - JsonProperty property, string parentTypeName, + JsonSchemaProperty property, string parentTypeName, TypeScriptTypeResolver typeResolver, TypeScriptGeneratorSettings settings) : base(property, classTemplateModel, typeResolver, settings) diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs index 7930922fc..19238c9c6 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs @@ -22,7 +22,7 @@ public class TypeScriptGenerator : GeneratorBase /// Initializes a new instance of the class. /// The schema. - public TypeScriptGenerator(JsonSchema4 schema) + public TypeScriptGenerator(JsonSchema schema) : this(schema, new TypeScriptGeneratorSettings()) { } @@ -122,7 +122,7 @@ protected override string GenerateFile(IEnumerable artifacts) /// The schema. /// The fallback type name. /// The code. - protected override CodeArtifact GenerateType(JsonSchema4 schema, string typeNameHint) + protected override CodeArtifact GenerateType(JsonSchema schema, string typeNameHint) { var typeName = _resolver.GetOrGenerateTypeName(schema, typeNameHint); diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs index 13b84a9dd..d42de9fa7 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs @@ -11,7 +11,7 @@ namespace NJsonSchema.CodeGeneration.TypeScript { - /// Generates the property name for a given TypeScript . + /// Generates the property name for a given TypeScript . public class TypeScriptPropertyNameGenerator : IPropertyNameGenerator { /// Gets or sets the reserved names. @@ -20,7 +20,7 @@ public class TypeScriptPropertyNameGenerator : IPropertyNameGenerator /// Generates the property name. /// The property. /// The new name. - public virtual string Generate(JsonProperty property) + public virtual string Generate(JsonSchemaProperty property) { var name = ConversionUtilities.ConvertToLowerCamelCase(property.Name .Replace("\"", string.Empty) diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs index 659fbe4a1..900da9ac4 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs @@ -34,7 +34,7 @@ public TypeScriptTypeResolver(TypeScriptGeneratorSettings settings) /// The type name hint to use when generating the type and the type name is missing. /// The type name. /// is . - public string ResolveConstructorInterfaceName(JsonSchema4 schema, bool isNullable, string typeNameHint) + public string ResolveConstructorInterfaceName(JsonSchema schema, bool isNullable, string typeNameHint) { return Resolve(schema, typeNameHint, true); } @@ -45,7 +45,7 @@ public string ResolveConstructorInterfaceName(JsonSchema4 schema, bool isNullabl /// The type name hint to use when generating the type and the type name is missing. /// The type name. /// is . - public override string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint) + public override string Resolve(JsonSchema schema, bool isNullable, string typeNameHint) { return Resolve(schema, typeNameHint, false); } @@ -53,7 +53,7 @@ public override string Resolve(JsonSchema4 schema, bool isNullable, string typeN /// Gets a value indicating whether the schema supports constructor conversion. /// The schema. /// The result. - public bool SupportsConstructorConversion(JsonSchema4 schema) + public bool SupportsConstructorConversion(JsonSchema schema) { return schema?.ActualSchema.ResponsibleDiscriminatorObject == null; } @@ -61,7 +61,7 @@ public bool SupportsConstructorConversion(JsonSchema4 schema) /// Checks whether the given schema should generate a type. /// The schema. /// True if the schema should generate a type. - protected override bool IsDefinitionTypeSchema(JsonSchema4 schema) + protected override bool IsDefinitionTypeSchema(JsonSchema schema) { if (schema.IsDictionary && !Settings.InlineNamedDictionaries) { @@ -71,7 +71,7 @@ protected override bool IsDefinitionTypeSchema(JsonSchema4 schema) return base.IsDefinitionTypeSchema(schema); } - private string Resolve(JsonSchema4 schema, string typeNameHint, bool addInterfacePrefix) + private string Resolve(JsonSchema schema, string typeNameHint, bool addInterfacePrefix) { if (schema == null) throw new ArgumentNullException(nameof(schema)); @@ -136,7 +136,7 @@ private string Resolve(JsonSchema4 schema, string typeNameHint, bool addInterfac GetOrGenerateTypeName(schema, typeNameHint); } - private string ResolveString(JsonSchema4 schema, string typeNameHint) + private string ResolveString(JsonSchema schema, string typeNameHint) { // TODO: Make this more generic (see DataConversionGenerator.IsDate) if (Settings.DateTimeType == TypeScriptDateTimeType.Date) @@ -172,12 +172,12 @@ private string ResolveString(JsonSchema4 schema, string typeNameHint) return "string"; } - private string ResolveInteger(JsonSchema4 schema, string typeNameHint) + private string ResolveInteger(JsonSchema schema, string typeNameHint) { return "number"; } - private string ResolveArrayOrTuple(JsonSchema4 schema, string typeNameHint, bool addInterfacePrefix) + private string ResolveArrayOrTuple(JsonSchema schema, string typeNameHint, bool addInterfacePrefix) { if (schema.Item != null) { @@ -202,7 +202,7 @@ private string ResolveArrayOrTuple(JsonSchema4 schema, string typeNameHint, bool return "any[]"; } - private string GetNullableItemType(JsonSchema4 schema, string itemType) + private string GetNullableItemType(JsonSchema schema, string itemType) { if (Settings.SupportsStrictNullChecks && schema.Item.IsNullable(Settings.SchemaType)) { diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptValueGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptValueGenerator.cs index 05e3551af..16b774b90 100644 --- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptValueGenerator.cs +++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptValueGenerator.cs @@ -37,7 +37,7 @@ public TypeScriptValueGenerator(TypeScriptGeneratorSettings settings) /// if set to true uses the default value from the schema if available. /// The type resolver. /// The code. - public override string GetDefaultValue(JsonSchema4 schema, bool allowsNull, string targetType, string typeNameHint, bool useSchemaDefault, TypeResolverBase typeResolver) + public override string GetDefaultValue(JsonSchema schema, bool allowsNull, string targetType, string typeNameHint, bool useSchemaDefault, TypeResolverBase typeResolver) { var value = base.GetDefaultValue(schema, allowsNull, targetType, typeNameHint, useSchemaDefault, typeResolver); if (value == null) @@ -51,7 +51,7 @@ public override string GetDefaultValue(JsonSchema4 schema, bool allowsNull, stri } } - var isOptional = (schema as JsonProperty)?.IsRequired == false; + var isOptional = (schema as JsonSchemaProperty)?.IsRequired == false; if (schema != null && allowsNull == false && isOptional == false) { if (typeResolver.GeneratesType(schema) && diff --git a/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs b/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs index ab258e94b..6a9ae6911 100644 --- a/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs @@ -12,12 +12,12 @@ namespace NJsonSchema.CodeGeneration public class DefaultEnumNameGenerator : IEnumNameGenerator { /// Generates the enumeration name/key of the given enumeration entry. - /// The index of the enumeration value (check and ). + /// The index of the enumeration value (check and ). /// The name/key. /// The value. /// The schema. /// The enumeration name. - public string Generate(int index, string name, object value, JsonSchema4 schema) + public string Generate(int index, string name, object value, JsonSchema schema) { if (string.IsNullOrEmpty(name)) { diff --git a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs index 3e9ad351c..5f5f86118 100644 --- a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs +++ b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs @@ -49,7 +49,7 @@ public ITemplate CreateTemplate(string language, string template, object model) /// The toolchain version. protected virtual string GetToolchainVersion() { - return JsonSchema4.ToolchainVersion; + return JsonSchema.ToolchainVersion; } /// Gets a Liquid template by name. diff --git a/src/NJsonSchema.CodeGeneration/GeneratorBase.cs b/src/NJsonSchema.CodeGeneration/GeneratorBase.cs index 6b09edbca..2432db745 100644 --- a/src/NJsonSchema.CodeGeneration/GeneratorBase.cs +++ b/src/NJsonSchema.CodeGeneration/GeneratorBase.cs @@ -36,7 +36,7 @@ protected GeneratorBase(object rootObject, TypeResolverBase typeResolver, CodeGe /// The code public string GenerateFile(string typeNameHint) { - var schema = (JsonSchema4)RootObject; + var schema = (JsonSchema)RootObject; return GenerateFile(schema, typeNameHint); } @@ -44,7 +44,7 @@ public string GenerateFile(string typeNameHint) /// The code public string GenerateFile() { - var schema = (JsonSchema4)RootObject; + var schema = (JsonSchema)RootObject; return GenerateFile(schema, schema.Title != null && Regex.IsMatch(schema.Title, "^[a-zA-Z0-9_]*$") ? schema.Title : null); } @@ -52,7 +52,7 @@ public string GenerateFile() /// The schema /// The type name hint. /// The code. - public IEnumerable GenerateTypes(JsonSchema4 schema, string typeNameHint) + public IEnumerable GenerateTypes(JsonSchema schema, string typeNameHint) { _resolver.Resolve(schema, false, typeNameHint); // register root type return GenerateTypes(); @@ -60,7 +60,7 @@ public IEnumerable GenerateTypes(JsonSchema4 schema, string typeNa /// Generates the the whole file containing all needed types. /// The code - public string GenerateFile(JsonSchema4 schema, string typeNameHint) + public string GenerateFile(JsonSchema schema, string typeNameHint) { var artifacts = GenerateTypes(schema, typeNameHint); return GenerateFile(artifacts); @@ -96,6 +96,6 @@ public virtual IEnumerable GenerateTypes() /// The schema. /// The type name hint. /// The code. - protected abstract CodeArtifact GenerateType(JsonSchema4 schema, string typeNameHint); + protected abstract CodeArtifact GenerateType(JsonSchema schema, string typeNameHint); } } \ No newline at end of file diff --git a/src/NJsonSchema.CodeGeneration/IEnumNameGenerator.cs b/src/NJsonSchema.CodeGeneration/IEnumNameGenerator.cs index 23248eac1..b8a7e8674 100644 --- a/src/NJsonSchema.CodeGeneration/IEnumNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration/IEnumNameGenerator.cs @@ -12,11 +12,11 @@ namespace NJsonSchema.CodeGeneration public interface IEnumNameGenerator { /// Generates the enumeration name/key of the given enumeration entry. - /// The index of the enumeration value (check and ). + /// The index of the enumeration value (check and ). /// The name/key. /// The value. /// The schema. /// The enumeration name. - string Generate(int index, string name, object value, JsonSchema4 schema); + string Generate(int index, string name, object value, JsonSchema schema); } } \ No newline at end of file diff --git a/src/NJsonSchema.CodeGeneration/IPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration/IPropertyNameGenerator.cs index d8df964ac..8b3eafc76 100644 --- a/src/NJsonSchema.CodeGeneration/IPropertyNameGenerator.cs +++ b/src/NJsonSchema.CodeGeneration/IPropertyNameGenerator.cs @@ -8,12 +8,12 @@ namespace NJsonSchema.CodeGeneration { - /// Generates the property name for a given . + /// Generates the property name for a given . public interface IPropertyNameGenerator { /// Generates the property name. /// The property. /// The new name. - string Generate(JsonProperty property); + string Generate(JsonSchemaProperty property); } } \ No newline at end of file diff --git a/src/NJsonSchema.CodeGeneration/JsonSchemaGraphUtilities.cs b/src/NJsonSchema.CodeGeneration/JsonSchemaGraphUtilities.cs index 6c166b84f..d486e5a92 100644 --- a/src/NJsonSchema.CodeGeneration/JsonSchemaGraphUtilities.cs +++ b/src/NJsonSchema.CodeGeneration/JsonSchemaGraphUtilities.cs @@ -19,7 +19,7 @@ public static class JsonSchemaGraphUtilities /// The schema. /// The root object. /// - public static IDictionary GetDerivedSchemas(this JsonSchema4 schema, object rootObject) + public static IDictionary GetDerivedSchemas(this JsonSchema schema, object rootObject) { var visitor = new DerivedSchemaVisitor(schema); visitor.VisitAsync(rootObject).GetAwaiter().GetResult(); @@ -28,17 +28,17 @@ public static IDictionary GetDerivedSchemas(this JsonSchema private class DerivedSchemaVisitor : JsonSchemaVisitorBase { - private readonly JsonSchema4 _baseSchema; + private readonly JsonSchema _baseSchema; - public Dictionary DerivedSchemas { get; } = new Dictionary(); + public Dictionary DerivedSchemas { get; } = new Dictionary(); - public DerivedSchemaVisitor(JsonSchema4 baseSchema) + public DerivedSchemaVisitor(JsonSchema baseSchema) { _baseSchema = baseSchema; } #pragma warning disable 1998 - protected override async Task VisitSchemaAsync(JsonSchema4 schema, string path, string typeNameHint) + protected override async Task VisitSchemaAsync(JsonSchema schema, string path, string typeNameHint) #pragma warning restore 1998 { if (schema.Inherits(_baseSchema) && _baseSchema != schema) diff --git a/src/NJsonSchema.CodeGeneration/Models/ClassTemplateModelBase.cs b/src/NJsonSchema.CodeGeneration/Models/ClassTemplateModelBase.cs index cee628f53..a0c0d7ef9 100644 --- a/src/NJsonSchema.CodeGeneration/Models/ClassTemplateModelBase.cs +++ b/src/NJsonSchema.CodeGeneration/Models/ClassTemplateModelBase.cs @@ -14,7 +14,7 @@ namespace NJsonSchema.CodeGeneration.Models /// The class template base class. public abstract class ClassTemplateModelBase : TemplateModelBase { - private readonly JsonSchema4 _schema; + private readonly JsonSchema _schema; private readonly object _rootObject; private readonly TypeResolverBase _resolver; @@ -22,7 +22,7 @@ public abstract class ClassTemplateModelBase : TemplateModelBase /// The resolver. /// The schema. /// The root object. - protected ClassTemplateModelBase(TypeResolverBase resolver, JsonSchema4 schema, object rootObject) + protected ClassTemplateModelBase(TypeResolverBase resolver, JsonSchema schema, object rootObject) { _schema = schema; _rootObject = rootObject; @@ -50,7 +50,7 @@ protected ClassTemplateModelBase(TypeResolverBase resolver, JsonSchema4 schema, /// The model of a derived class. public class DerivedClassModel { - internal DerivedClassModel(string typeName, JsonSchema4 schema, OpenApiDiscriminator discriminator, TypeResolverBase resolver) + internal DerivedClassModel(string typeName, JsonSchema schema, OpenApiDiscriminator discriminator, TypeResolverBase resolver) { var mapping = discriminator.Mapping.SingleOrDefault(m => m.Value.ActualTypeSchema == schema.ActualTypeSchema); diff --git a/src/NJsonSchema.CodeGeneration/Models/PropertyModelBase.cs b/src/NJsonSchema.CodeGeneration/Models/PropertyModelBase.cs index a2b5b3dab..83bfd50d4 100644 --- a/src/NJsonSchema.CodeGeneration/Models/PropertyModelBase.cs +++ b/src/NJsonSchema.CodeGeneration/Models/PropertyModelBase.cs @@ -15,7 +15,7 @@ namespace NJsonSchema.CodeGeneration.Models public abstract class PropertyModelBase { private readonly ClassTemplateModelBase _classTemplateModel; - private readonly JsonProperty _property; + private readonly JsonSchemaProperty _property; private readonly TypeResolverBase _typeResolver; private readonly CodeGeneratorSettingsBase _settings; @@ -25,7 +25,7 @@ public abstract class PropertyModelBase /// The type resolver. /// The settings. protected PropertyModelBase( - JsonProperty property, + JsonSchemaProperty property, ClassTemplateModelBase classTemplateModel, TypeResolverBase typeResolver, CodeGeneratorSettingsBase settings) diff --git a/src/NJsonSchema.CodeGeneration/Models/TemplateModelBase.cs b/src/NJsonSchema.CodeGeneration/Models/TemplateModelBase.cs index 6fce3deeb..d8a57d047 100644 --- a/src/NJsonSchema.CodeGeneration/Models/TemplateModelBase.cs +++ b/src/NJsonSchema.CodeGeneration/Models/TemplateModelBase.cs @@ -12,6 +12,6 @@ namespace NJsonSchema.CodeGeneration.Models public class TemplateModelBase { /// Gets the NJsonSchema toolchain version. - public string ToolchainVersion => JsonSchema4.ToolchainVersion; + public string ToolchainVersion => JsonSchema.ToolchainVersion; } } diff --git a/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs b/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs index 6b1e7319b..f152f4428 100644 --- a/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs +++ b/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs @@ -15,7 +15,7 @@ namespace NJsonSchema.CodeGeneration public abstract class TypeResolverBase { private readonly CodeGeneratorSettingsBase _settings; - private readonly Dictionary _generatedTypeNames = new Dictionary(); + private readonly Dictionary _generatedTypeNames = new Dictionary(); /// Initializes a new instance of the class. /// The settings. @@ -25,13 +25,13 @@ protected TypeResolverBase(CodeGeneratorSettingsBase settings) } /// Gets the registered schemas and with their type names. - public IDictionary Types => _generatedTypeNames.ToDictionary(p => p.Key, p => p.Value); + public IDictionary Types => _generatedTypeNames.ToDictionary(p => p.Key, p => p.Value); /// Tries to resolve the schema and returns null if there was a problem. /// The schema. /// The type name hint. /// The type name. - public string TryResolve(JsonSchema4 schema, string typeNameHint) + public string TryResolve(JsonSchema schema, string typeNameHint) { return schema != null ? Resolve(schema, false, typeNameHint) : null; } @@ -41,13 +41,13 @@ public string TryResolve(JsonSchema4 schema, string typeNameHint) /// Specifies whether the given type usage is nullable. /// The type name hint to use when generating the type and the type name is missing. /// The type name. - public abstract string Resolve(JsonSchema4 schema, bool isNullable, string typeNameHint); + public abstract string Resolve(JsonSchema schema, bool isNullable, string typeNameHint); /// Gets or generates the type name for the given schema. /// The schema. /// The type name hint. /// The type name. - public virtual string GetOrGenerateTypeName(JsonSchema4 schema, string typeNameHint) + public virtual string GetOrGenerateTypeName(JsonSchema schema, string typeNameHint) { schema = RemoveNullability(schema).ActualSchema; @@ -64,7 +64,7 @@ public virtual string GetOrGenerateTypeName(JsonSchema4 schema, string typeNameH /// Adds all schemas to the resolver. /// The schema definitions. - public void RegisterSchemaDefinitions(IDictionary definitions) + public void RegisterSchemaDefinitions(IDictionary definitions) { if (definitions != null) { @@ -83,7 +83,7 @@ public void RegisterSchemaDefinitions(IDictionary definitio /// Removes a nullable oneOf reference if available. /// The schema. /// The actually resolvable schema - public JsonSchema4 RemoveNullability(JsonSchema4 schema) + public JsonSchema RemoveNullability(JsonSchema schema) { // TODO: Method on JsonSchema4? return schema.OneOf.FirstOrDefault(o => !o.IsNullable(SchemaType.JsonSchema)) ?? schema; @@ -93,7 +93,7 @@ public JsonSchema4 RemoveNullability(JsonSchema4 schema) /// and removes a nullable oneOf reference if available. /// The schema. /// The actually resolvable schema - public JsonSchema4 GetResolvableSchema(JsonSchema4 schema) + public JsonSchema GetResolvableSchema(JsonSchema schema) { schema = RemoveNullability(schema); return IsDefinitionTypeSchema(schema.ActualSchema) ? schema : schema.ActualSchema; @@ -103,7 +103,7 @@ public JsonSchema4 GetResolvableSchema(JsonSchema4 schema) /// or is an inline type (e.g. string, number, etc.). Warning: Enum will also return true. /// /// - public bool GeneratesType(JsonSchema4 schema) + public bool GeneratesType(JsonSchema schema) { schema = GetResolvableSchema(schema); return schema.HasReference || (schema.IsObject && !schema.IsDictionary && !schema.IsAnyType); @@ -112,7 +112,7 @@ public bool GeneratesType(JsonSchema4 schema) /// Checks whether the given schema from definitions should generate a type. /// The schema. /// True if the schema should generate a type. - protected virtual bool IsDefinitionTypeSchema(JsonSchema4 schema) + protected virtual bool IsDefinitionTypeSchema(JsonSchema schema) { return !schema.IsTuple && !schema.IsDictionary && @@ -127,7 +127,7 @@ protected virtual bool IsDefinitionTypeSchema(JsonSchema4 schema) /// The schema. /// The fallback type (e.g. 'object'). /// The type. - protected string ResolveDictionaryValueType(JsonSchema4 schema, string fallbackType) + protected string ResolveDictionaryValueType(JsonSchema schema, string fallbackType) { if (schema.AdditionalPropertiesSchema != null) { @@ -154,7 +154,7 @@ protected string ResolveDictionaryValueType(JsonSchema4 schema, string fallbackT /// The schema. /// The fallback type (e.g. 'object'). /// The type. - protected string ResolveDictionaryKeyType(JsonSchema4 schema, string fallbackType) + protected string ResolveDictionaryKeyType(JsonSchema schema, string fallbackType) { if (schema.DictionaryKey != null) { diff --git a/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs b/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs index 3ef2475e6..3c2a95673 100644 --- a/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs +++ b/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs @@ -47,12 +47,12 @@ protected ValueGeneratorBase(CodeGeneratorSettingsBase settings) /// if set to true uses the default value from the schema if available. /// The type resolver. /// The code. - public virtual string GetDefaultValue(JsonSchema4 schema, bool allowsNull, string targetType, string typeNameHint, bool useSchemaDefault, TypeResolverBase typeResolver) + public virtual string GetDefaultValue(JsonSchema schema, bool allowsNull, string targetType, string typeNameHint, bool useSchemaDefault, TypeResolverBase typeResolver) { if (schema.Default == null || !useSchemaDefault) return null; - var actualSchema = schema is JsonProperty ? ((JsonProperty)schema).ActualTypeSchema : schema.ActualSchema; + var actualSchema = schema is JsonSchemaProperty ? ((JsonSchemaProperty)schema).ActualTypeSchema : schema.ActualSchema; if (actualSchema.IsEnumeration && !actualSchema.Type.HasFlag(JsonObjectType.Object) && actualSchema.Type != JsonObjectType.None) { return GetEnumDefaultValue(schema, actualSchema, typeNameHint, typeResolver); @@ -91,7 +91,7 @@ public virtual string GetDefaultValue(JsonSchema4 schema, bool allowsNull, strin /// The type name hint. /// The type resolver. /// The enum default value. - protected virtual string GetEnumDefaultValue(JsonSchema4 schema, JsonSchema4 actualSchema, string typeNameHint, TypeResolverBase typeResolver) + protected virtual string GetEnumDefaultValue(JsonSchema schema, JsonSchema actualSchema, string typeNameHint, TypeResolverBase typeResolver) { var typeName = typeResolver.Resolve(actualSchema, false, typeNameHint); @@ -106,7 +106,7 @@ protected virtual string GetEnumDefaultValue(JsonSchema4 schema, JsonSchema4 act /// Gets the default value as string literal. /// The schema. /// The string literal. - protected string GetDefaultAsStringLiteral(JsonSchema4 schema) + protected string GetDefaultAsStringLiteral(JsonSchema schema) { return "\"" + ConversionUtilities.ConvertToStringLiteral(schema.Default.ToString()) + "\""; } diff --git a/src/NJsonSchema.Demo.Performance/Program.cs b/src/NJsonSchema.Demo.Performance/Program.cs index 951d223c3..7587f4be3 100644 --- a/src/NJsonSchema.Demo.Performance/Program.cs +++ b/src/NJsonSchema.Demo.Performance/Program.cs @@ -18,7 +18,7 @@ private static async Task Run() stopwatch.Start(); for (int i = 0; i < 500; i++) { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); } stopwatch.Stop(); diff --git a/src/NJsonSchema.Demo/Program.cs b/src/NJsonSchema.Demo/Program.cs index f094f2f45..730c45389 100644 --- a/src/NJsonSchema.Demo/Program.cs +++ b/src/NJsonSchema.Demo/Program.cs @@ -81,7 +81,7 @@ private static void RunTest(string file, JObject suite, JToken value, bool expec { try { - var schema = JsonSchema4.FromJsonAsync(suite["schema"].ToString(), Path.GetDirectoryName(file)).GetAwaiter().GetResult(); + var schema = JsonSchema.FromJsonAsync(suite["schema"].ToString(), Path.GetDirectoryName(file)).GetAwaiter().GetResult(); var errors = schema.Validate(value); var success = expectedResult ? errors.Count == 0 : errors.Count > 0; diff --git a/src/NJsonSchema.Tests/Conversion/ArrayTypeToSchemaTests.cs b/src/NJsonSchema.Tests/Conversion/ArrayTypeToSchemaTests.cs index 4b11814a0..97632dba7 100644 --- a/src/NJsonSchema.Tests/Conversion/ArrayTypeToSchemaTests.cs +++ b/src/NJsonSchema.Tests/Conversion/ArrayTypeToSchemaTests.cs @@ -28,7 +28,7 @@ public async Task When_converting_type_inheriting_from_dictionary_then_it_should dict.Add("bar", new List { "a", "b" }); var json = JsonConvert.SerializeObject(dict); - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Assert @@ -90,7 +90,7 @@ public class MySubtype private async Task When_converting_smth_then_items_must_correctly_be_loaded(string propertyName) { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Conversion/SchemaReferenceTests.cs b/src/NJsonSchema.Tests/Conversion/SchemaReferenceTests.cs index b3576abe0..5dffc37d3 100644 --- a/src/NJsonSchema.Tests/Conversion/SchemaReferenceTests.cs +++ b/src/NJsonSchema.Tests/Conversion/SchemaReferenceTests.cs @@ -11,7 +11,7 @@ public async Task When_converting_a_circular_referencing_person_type_then_refere //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -24,7 +24,7 @@ public async Task When_converting_a_circular_referencing_car_type_then_reference //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(schema, schema.Properties["Person"].ActualTypeSchema.Properties["Car"].ActualTypeSchema); @@ -34,7 +34,7 @@ public async Task When_converting_a_circular_referencing_car_type_then_reference public async Task When_converting_a_referencing_type_then_path_is_in_json() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); @@ -47,7 +47,7 @@ public async Task When_converting_a_referencing_type_then_path_is_in_json() public async Task When_converting_a_referencing_type_then_absolute_reference_path_is_in_json() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); @@ -85,7 +85,7 @@ public async Task When_ref_is_nested_then_it_should_be_resolved() }"; /// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); /// Assert var jsonOutput = schema.ToJson(); diff --git a/src/NJsonSchema.Tests/Conversion/TypeToSchemaTests.cs b/src/NJsonSchema.Tests/Conversion/TypeToSchemaTests.cs index 8301da5d9..717ccb9f7 100644 --- a/src/NJsonSchema.Tests/Conversion/TypeToSchemaTests.cs +++ b/src/NJsonSchema.Tests/Conversion/TypeToSchemaTests.cs @@ -17,11 +17,11 @@ public class TypeToSchemaTests public async Task When_converting_in_round_trip_then_json_should_be_the_same() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var schemaData1 = JsonConvert.SerializeObject(schema, Formatting.Indented); - var schema2 = JsonConvert.DeserializeObject(schemaData1); + var schema2 = JsonConvert.DeserializeObject(schemaData1); var schemaData2 = JsonConvert.SerializeObject(schema2, Formatting.Indented); //// Assert @@ -32,7 +32,7 @@ public async Task When_converting_in_round_trip_then_json_should_be_the_same() public async Task When_converting_simple_property_then_property_must_be_in_schema() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Assert @@ -48,7 +48,7 @@ public async Task When_converting_simple_property_then_property_must_be_in_schem public async Task When_converting_nullable_simple_property_then_property_must_be_in_schema() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.Integer | JsonObjectType.Null, schema.Properties["NullableInteger"].Type); @@ -61,7 +61,7 @@ public async Task When_converting_nullable_simple_property_then_property_must_be public async Task When_converting_property_with_description_then_description_should_be_in_schema() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal("Test", schema.Properties["Integer"].Description); @@ -71,7 +71,7 @@ public async Task When_converting_property_with_description_then_description_sho public async Task When_converting_required_property_then_it_should_be_required_in_schema() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties["RequiredReference"].IsRequired); @@ -81,7 +81,7 @@ public async Task When_converting_required_property_then_it_should_be_required_i public async Task When_converting_regex_property_then_it_should_be_set_as_pattern() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal("regex", schema.Properties["RegexString"].Pattern); @@ -97,7 +97,7 @@ public class ClassWithRegexDictionaryProperty public async Task When_dictionary_property_has_regex_attribute_then_regex_is_added_to_additionalProperties() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -109,7 +109,7 @@ public async Task When_dictionary_property_has_regex_attribute_then_regex_is_add public async Task When_converting_range_property_then_it_should_be_set_as_min_max() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(5, schema.Properties["RangeInteger"].Minimum); @@ -120,7 +120,7 @@ public async Task When_converting_range_property_then_it_should_be_set_as_min_ma public async Task When_converting_not_nullable_properties_then_they_should_have_null_type() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.False(schema.Properties["Integer"].IsRequired); @@ -140,7 +140,7 @@ public async Task When_converting_not_nullable_properties_then_they_should_have_ public async Task When_generating_nullable_primitive_properties_then_they_should_have_null_type() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties["NullableInteger"].Type.HasFlag(JsonObjectType.Null)); @@ -153,7 +153,7 @@ public async Task When_generating_nullable_primitive_properties_then_they_should public async Task When_property_is_renamed_then_the_name_must_be_correct() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties.ContainsKey("abc")); @@ -164,7 +164,7 @@ public async Task When_property_is_renamed_then_the_name_must_be_correct() public async Task When_converting_object_then_it_should_be_correct() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Assert @@ -177,7 +177,7 @@ public async Task When_converting_object_then_it_should_be_correct() public async Task When_converting_enum_then_enum_array_must_be_set() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -199,7 +199,7 @@ public class ClassWithJObjectProperty public async Task When_type_is_JObject_then_generated_type_is_any() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); var property = schema.Properties["Property"]; @@ -231,7 +231,7 @@ public async Task When_converting_list_then_items_must_correctly_be_loaded() private async Task When_converting_smth_then_items_must_correctly_be_loaded(string propertyName) { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert var property = schema.Properties[propertyName]; diff --git a/src/NJsonSchema.Tests/Generation/AbstractGenerationTests.cs b/src/NJsonSchema.Tests/Generation/AbstractGenerationTests.cs index fef75af17..acdc6d724 100644 --- a/src/NJsonSchema.Tests/Generation/AbstractGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/AbstractGenerationTests.cs @@ -14,7 +14,7 @@ public abstract class AbstractClass public async Task When_class_is_abstract_then_is_abstract_is_true() { /// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Assert @@ -31,7 +31,7 @@ public class NotAbstractClass public async Task When_class_is_not_abstract_then_is_abstract_is_false() { /// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Assert diff --git a/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs b/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs index fe823539c..1325adc44 100644 --- a/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/AnnotationsGenerationTests.cs @@ -30,7 +30,7 @@ public class MyPoint public async Task When_class_annotation_is_available_then_type_and_format_can_be_customized() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -45,7 +45,7 @@ public async Task When_class_annotation_is_available_then_type_and_format_can_be public async Task When_property_annotation_is_available_then_type_and_format_can_be_customized() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -66,7 +66,7 @@ public class DateAttributeClass public async Task When_DateTime_property_has_JsonSchemaDate_attribute_then_format_and_type_is_correct() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Act @@ -89,7 +89,7 @@ public async Task When_multipleOf_attribute_is_available_then_value_is_set_in_sc //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Number"]; //// Assert @@ -118,7 +118,7 @@ public async Task When_multipleOf_is_fraction_then_it_is_validated_correctly() } string jsonData = JsonConvert.SerializeObject(testClasses, Formatting.Indented); - var schema = await JsonSchema4.FromJsonAsync(@"{ + var schema = await JsonSchema.FromJsonAsync(@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""array"", ""items"": { @@ -162,7 +162,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() public async Task When_class_has_array_item_type_defined_then_schema_has_this_item_type() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var data = schema.ToJson(); @@ -180,7 +180,7 @@ public class ArrayModel : List public async Task When_class_has_array_item_type_defined_then_schema_has_this_item_type2() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync>(); + var schema = await JsonSchema.FromTypeAsync>(); //// Act var data = schema.ToJson(); @@ -205,7 +205,7 @@ public struct MyStruct public async Task When_property_is_struct_then_it_is_not_nullable() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var data = schema.ToJson(); @@ -227,7 +227,7 @@ public async Task When_StringLengthAttribute_is_set_then_minLength_and_maxLenght //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert var property = schema.Properties["Foo"]; @@ -248,7 +248,7 @@ public class MinLengthAttributeClass [Fact] public async Task When_MinLengthAttribute_is_set_then_minItems_or_minLength_is_set() { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var arrayProperty = schema.Properties["Items"]; Assert.Equal(1, arrayProperty.MinItems); @@ -269,7 +269,7 @@ public class MaxLengthAttributeClass [Fact] public async Task When_MaxLengthAttribute_is_set_then_maxItems_or_maxLength_is_set() { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var arrayProperty = schema.Properties["Items"]; Assert.Equal(100, arrayProperty.MaxItems); @@ -290,7 +290,7 @@ public async Task When_RequiredAttribute_is_set_with_AllowEmptyStrings_false_the //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert var property = schema.Properties["Foo"]; @@ -311,7 +311,7 @@ public async Task When_RequiredAttribute_is_set_with_AllowEmptyStrings_false_on_ //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -362,7 +362,7 @@ public class DataTypeAttributeClass [InlineData(nameof(DataTypeAttributeClass.Url2), "uri")] public async Task When_DataTypeAttribute_is_set_then_the_format_property_should_come_from_the_attribute(string propertyName, string expectedFormat) { - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties[propertyName]; Assert.Equal(expectedFormat, property.Format); @@ -388,7 +388,7 @@ public class Student : Person public async Task When_class_is_ignored_then_it_is_not_in_definitions() { /// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Assert diff --git a/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs b/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs index 3336c5e41..d57699120 100644 --- a/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/ArrayGenerationTests.cs @@ -19,7 +19,7 @@ public class ClassWithJArray public async Task When_property_is_JArray_then_schema_with_any_array_is_generated() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); var json = schema.ToJson(); //// Assert @@ -45,7 +45,7 @@ public class SomeModelCollectionResponse : List { } public async Task When_class_inherits_from_list_then_schema_is_inlined_and_type_is_array() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); var json = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/AttributeGenerationTests.cs b/src/NJsonSchema.Tests/Generation/AttributeGenerationTests.cs index 20ea4663f..1c3eeef9d 100644 --- a/src/NJsonSchema.Tests/Generation/AttributeGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/AttributeGenerationTests.cs @@ -15,7 +15,7 @@ public async Task When_minLength_and_maxLength_attribute_are_set_on_array_then_m //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Items"]; //// Assert @@ -29,7 +29,7 @@ public async Task When_minLength_and_maxLength_attribute_are_set_on_string_then_ //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["String"]; //// Assert @@ -45,7 +45,7 @@ public async Task When_Range_attribute_is_set_on_double_then_minimum_and_maximum //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Double"]; //// Assert @@ -59,7 +59,7 @@ public async Task When_Range_attribute_has_double_max_then_max_is_not_set() //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["DoubleOnlyMin"]; //// Assert @@ -73,7 +73,7 @@ public async Task When_Range_attribute_is_set_on_integer_then_minimum_and_maximu //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Integer"]; //// Assert @@ -88,7 +88,7 @@ public async Task When_display_attribute_is_available_then_name_and_description_ //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Display"]; //// Assert @@ -103,7 +103,7 @@ public async Task When_description_attribute_is_available_then_description_are_r //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Description"]; //// Assert @@ -117,7 +117,7 @@ public async Task When_required_attribute_is_available_then_property_is_required //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Required"]; //// Assert @@ -131,7 +131,7 @@ public async Task When_required_attribute_is_not_available_then_property_is_can_ //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Description"]; //// Assert @@ -146,7 +146,7 @@ public async Task When_ReadOnly_is_set_then_readOnly_is_set_in_schema() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["ReadOnly"]; //// Assert @@ -201,7 +201,7 @@ public async Task When_range_has_type_and_strings_then_it_is_processed_correctly //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var property = schema.Properties["Foo"]; //// Assert diff --git a/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs b/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs index cda71cab9..e18a3b79a 100644 --- a/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs +++ b/src/NJsonSchema.Tests/Generation/ContractResolverTests.cs @@ -18,7 +18,7 @@ public class ContractResolverTests #endif public async Task Properties_should_match_custom_resolver() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { ContractResolver = new CustomContractResolver() }); @@ -43,7 +43,7 @@ public async Task Properties_should_match_custom_resolver() /// public class CustomContractResolver : CamelCasePropertyNamesContractResolver { - protected override Newtonsoft.Json.Serialization.JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var prop = base.CreateProperty(member, memberSerialization); if (!prop.Writable && member.GetCustomAttribute(true) == null) @@ -55,7 +55,7 @@ protected override JsonContract CreateContract(Type objectType) { JsonContract contract = base.CreateContract(objectType); // by default a type that can convert to string and that is also an enum will have an array contract, but serialize to a string!. fix this - if (contract is JsonArrayContract && typeof(IEnumerable).IsAssignableFrom(objectType) + if (contract is JsonArrayContract && typeof(IEnumerable).IsAssignableFrom(objectType) && CanNonSystemTypeDescriptorConvertString(objectType)) contract = CreateStringContract(objectType); @@ -84,7 +84,9 @@ public static bool CanNonSystemTypeDescriptorConvertString(Type type) public class Person { public string FirstName { get; set; } + public int NameLength => FirstName.Length; + public LocationPath Location { get; set; } } diff --git a/src/NJsonSchema.Tests/Generation/DefaultTypeNameGeneratorTests.cs b/src/NJsonSchema.Tests/Generation/DefaultTypeNameGeneratorTests.cs index a243f9b20..4f769e1f2 100644 --- a/src/NJsonSchema.Tests/Generation/DefaultTypeNameGeneratorTests.cs +++ b/src/NJsonSchema.Tests/Generation/DefaultTypeNameGeneratorTests.cs @@ -26,7 +26,7 @@ public void When_type_name_is_genererated_then_it_corret() foreach (var p in tests) { //// Act - var name = generator.Generate(new JsonSchema4(), p.Key, new List()); + var name = generator.Generate(new JsonSchema(), p.Key, new List()); //// Assert Assert.Equal(p.Value, name); diff --git a/src/NJsonSchema.Tests/Generation/DictionaryTests.cs b/src/NJsonSchema.Tests/Generation/DictionaryTests.cs index 26e9de221..08ccc1af5 100644 --- a/src/NJsonSchema.Tests/Generation/DictionaryTests.cs +++ b/src/NJsonSchema.Tests/Generation/DictionaryTests.cs @@ -26,7 +26,7 @@ public class EnumKeyDictionaryTest public async Task When_dictionary_key_is_enum_then_csharp_has_enum_key() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Assert @@ -44,7 +44,7 @@ public async Task When_dictionary_key_is_enum_then_csharp_has_enum_key() public async Task When_value_type_is_nullable_then_json_schema_is_nullable() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Assert @@ -56,7 +56,7 @@ public async Task When_value_type_is_nullable_then_json_schema_is_nullable() public async Task When_value_type_is_nullable_then_json_schema_is_nullable_Swagger2() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2, GenerateCustomNullableProperties = true diff --git a/src/NJsonSchema.Tests/Generation/EnumGenerationTests.cs b/src/NJsonSchema.Tests/Generation/EnumGenerationTests.cs index 6f1c4787a..3e014c86e 100644 --- a/src/NJsonSchema.Tests/Generation/EnumGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/EnumGenerationTests.cs @@ -35,7 +35,7 @@ public async Task When_property_is_integer_enum_then_schema_has_enum() //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer, GenerateEnumMappingDescription = true @@ -60,7 +60,7 @@ public async Task When_string_and_integer_enum_used_then_two_refs_are_generated( //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -81,7 +81,7 @@ public async Task When_property_is_string_enum_then_schema_has_enum() //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.String, GenerateEnumMappingDescription = true @@ -105,7 +105,7 @@ public async Task When_enum_is_generated_then_names_are_set() //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -130,7 +130,7 @@ public async Task When_enum_property_is_generated_then_enum_is_referenced() //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2, DefaultEnumHandling = EnumHandling.Integer @@ -160,7 +160,7 @@ public enum MyEnumeration public async Task When_string_enum_property_has_default_then_default_is_converted_to_string() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); //// Act var json = schema.ToJson(); @@ -183,7 +183,7 @@ public bool ShouldSerializeEnumValue() public async Task When_enum_property_has_should_serialize_then_no_npe() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings()); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings()); //// Act var json = schema.ToJson(); diff --git a/src/NJsonSchema.Tests/Generation/EnumTests.cs b/src/NJsonSchema.Tests/Generation/EnumTests.cs index 4b4f1316d..1f5779ca6 100644 --- a/src/NJsonSchema.Tests/Generation/EnumTests.cs +++ b/src/NJsonSchema.Tests/Generation/EnumTests.cs @@ -42,7 +42,7 @@ public async Task When_enum_is_used_multiple_times_in_array_then_it_is_always_re // Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -64,7 +64,7 @@ public async Task When_property_is_dictionary_with_enum_value_then_it_is_referen // Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); @@ -96,7 +96,7 @@ public async Task When_SerializerSettings_has_CamelCase_StringEnumConverter_then }; // Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var json = schema.ToJson(); // Assert @@ -121,7 +121,7 @@ public async Task When_enum_has_FlagsAttribute_then_custom_property_is_set() // Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.String }); @@ -145,7 +145,7 @@ public async Task When_enum_does_not_have_FlagsAttribute_then_custom_property_is // Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.String }); diff --git a/src/NJsonSchema.Tests/Generation/ExceptionTypeTests.cs b/src/NJsonSchema.Tests/Generation/ExceptionTypeTests.cs index 4e3afc741..ce551239c 100644 --- a/src/NJsonSchema.Tests/Generation/ExceptionTypeTests.cs +++ b/src/NJsonSchema.Tests/Generation/ExceptionTypeTests.cs @@ -17,7 +17,7 @@ public class MyException : Exception public async Task When_exception_schema_is_generated_then_special_properties_are_generated_and_JsonProperty_attribute_used() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.Tests/Generation/ExcplicitInterfacePropertyTests.cs b/src/NJsonSchema.Tests/Generation/ExcplicitInterfacePropertyTests.cs index 1576f069a..e3f399a87 100644 --- a/src/NJsonSchema.Tests/Generation/ExcplicitInterfacePropertyTests.cs +++ b/src/NJsonSchema.Tests/Generation/ExcplicitInterfacePropertyTests.cs @@ -38,7 +38,7 @@ public async Task When_a_property_is_explicit_interface_then_it_is_not_added_to_ //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(1, schema.Properties.Count); diff --git a/src/NJsonSchema.Tests/Generation/ExtensionDataGenerationTests.cs b/src/NJsonSchema.Tests/Generation/ExtensionDataGenerationTests.cs index b2d0c4fca..bad92fc97 100644 --- a/src/NJsonSchema.Tests/Generation/ExtensionDataGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/ExtensionDataGenerationTests.cs @@ -20,7 +20,7 @@ public class ClassWithExtensionData public async Task When_class_has_property_with_JsonExtensionDataAttribute_on_property_then_AdditionalProperties_schema_is_set() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); var json = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/FieldGenerationTests.cs b/src/NJsonSchema.Tests/Generation/FieldGenerationTests.cs index 630d37e7b..3cabc075f 100644 --- a/src/NJsonSchema.Tests/Generation/FieldGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/FieldGenerationTests.cs @@ -17,7 +17,7 @@ public async Task When_public_field_is_available_then_it_is_added_as_property() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/FlattenInheritanceHierarchyTests.cs b/src/NJsonSchema.Tests/Generation/FlattenInheritanceHierarchyTests.cs index 6d918bec1..9fc6f47ae 100644 --- a/src/NJsonSchema.Tests/Generation/FlattenInheritanceHierarchyTests.cs +++ b/src/NJsonSchema.Tests/Generation/FlattenInheritanceHierarchyTests.cs @@ -29,7 +29,7 @@ public async Task When_FlattenInheritanceHierarchy_is_enabled_then_all_propertie }; //// Act - var schema = await JsonSchema4.FromTypeAsync(typeof(Teacher), settings); + var schema = await JsonSchema.FromTypeAsync(typeof(Teacher), settings); var data = schema.ToJson(); //// Assert @@ -69,7 +69,7 @@ public async Task When_FlattenInheritanceHierarchy_is_enabled_then_all_interface }; //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var data = schema.ToJson(); //// Assert @@ -99,7 +99,7 @@ public async Task When_class_inherits_from_dictionary_then_flatten_inheritance_a }; //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var data = schema.ToJson(); //// Assert @@ -115,7 +115,7 @@ public async Task When_class_inherits_from_dictionary_then_flatten_inheritance_w }; //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var data = schema.ToJson(); //// Assert @@ -144,7 +144,7 @@ public async Task When_JsonSchemaFlattenAttribute_is_used_on_class_then_inherite var settings = new JsonSchemaGeneratorSettings(); //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var data = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/GenericTests.cs b/src/NJsonSchema.Tests/Generation/GenericTests.cs index ad39b4fed..6daff5574 100644 --- a/src/NJsonSchema.Tests/Generation/GenericTests.cs +++ b/src/NJsonSchema.Tests/Generation/GenericTests.cs @@ -25,7 +25,7 @@ public IEnumerator GetEnumerator() public async Task When_class_inherits_from_IEnumerable_then_it_should_become_a_json_array_type() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); @@ -44,7 +44,7 @@ public class A public async Task When_open_generic_type_is_generated_then_no_exception_is_thrown() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(typeof(A<>)); + var schema = await JsonSchema.FromTypeAsync(typeof(A<>)); //// Act var json = schema.ToJson(); diff --git a/src/NJsonSchema.Tests/Generation/IgnoredPropertyTests.cs b/src/NJsonSchema.Tests/Generation/IgnoredPropertyTests.cs index e1f13d8ac..cead41730 100644 --- a/src/NJsonSchema.Tests/Generation/IgnoredPropertyTests.cs +++ b/src/NJsonSchema.Tests/Generation/IgnoredPropertyTests.cs @@ -22,7 +22,7 @@ public class Mno public async Task When_field_has_JsonIgnoreAttribute_then_it_is_ignored() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); @@ -44,7 +44,7 @@ public class Xyz public async Task When_field_has_no_DataMemberAttribute_then_it_is_ignored() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); @@ -76,7 +76,7 @@ public Foo() public async Task When_indexer_property_has_ignore_attribute_then_it_is_ignored() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); diff --git a/src/NJsonSchema.Tests/Generation/InheritanceTests.cs b/src/NJsonSchema.Tests/Generation/InheritanceTests.cs index 7e43defa8..617a0e0d6 100644 --- a/src/NJsonSchema.Tests/Generation/InheritanceTests.cs +++ b/src/NJsonSchema.Tests/Generation/InheritanceTests.cs @@ -40,7 +40,7 @@ public async Task When_more_properties_are_defined_in_allOf_and_type_none_then_a }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Assert Assert.NotNull(schema.InheritedSchema); @@ -72,7 +72,7 @@ public async Task When_allOf_schema_is_object_type_then_it_is_an_inherited_schem }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Assert Assert.NotNull(schema.InheritedSchema); @@ -86,7 +86,7 @@ public async Task When_generating_type_with_inheritance_then_allOf_has_one_item( //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.NotNull(schema.ActualProperties["Class"]); @@ -112,7 +112,7 @@ public async Task When_generating_type_with_inheritance_and_flattening_then_sche //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { FlattenInheritanceHierarchy = true }); @@ -164,7 +164,7 @@ public async Task When_root_schema_is_inherited_then_schema_is_generated() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var data = schema.ToJson(); //// Assert @@ -202,7 +202,7 @@ public async Task When_discriminator_is_externally_defined_then_it_is_generated( }; //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var data = schema.ToJson(); //// Assert @@ -275,7 +275,7 @@ public async Task Existing_string_property_can_be_discriminant() //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.NotNull(schema.Properties["Kind"]); @@ -299,7 +299,7 @@ public async Task Existing_non_string_property_cant_be_discriminant() //// Arrange //// Act - Task GetSchema() => JsonSchema4.FromTypeAsync(); + Task GetSchema() => JsonSchema.FromTypeAsync(); //// Assert await Assert.ThrowsAsync(GetSchema); @@ -325,7 +325,7 @@ public async Task When_class_inherits_from_dictionary_then_allOf_contains_base_d }; //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var json = schema.ToJson(); //// Assert @@ -367,7 +367,7 @@ public async Task When_class_with_discriminator_has_base_class_then_mapping_is_p }; //// Act - var schema = await JsonSchema4.FromTypeAsync(settings); + var schema = await JsonSchema.FromTypeAsync(settings); var json = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/InterfaceTests.cs b/src/NJsonSchema.Tests/Generation/InterfaceTests.cs index 5dad3bc3b..c325156b3 100644 --- a/src/NJsonSchema.Tests/Generation/InterfaceTests.cs +++ b/src/NJsonSchema.Tests/Generation/InterfaceTests.cs @@ -31,7 +31,7 @@ public async Task When_class_inherits_from_interface_then_properties_for_interfa //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { GenerateAbstractProperties = true }); diff --git a/src/NJsonSchema.Tests/Generation/JsonPropertyAttributeTests.cs b/src/NJsonSchema.Tests/Generation/JsonPropertyAttributeTests.cs index 1c07d8eef..a0de32135 100644 --- a/src/NJsonSchema.Tests/Generation/JsonPropertyAttributeTests.cs +++ b/src/NJsonSchema.Tests/Generation/JsonPropertyAttributeTests.cs @@ -10,7 +10,7 @@ public class JsonPropertyAttributeTests public async Task When_name_of_JsonPropertyAttribute_is_set_then_it_is_used_as_json_property_name() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var property = schema.Properties["NewName"]; @@ -23,7 +23,7 @@ public async Task When_name_of_JsonPropertyAttribute_is_set_then_it_is_used_as_j public async Task When_required_is_always_in_JsonPropertyAttribute_then_the_property_is_required() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var property = schema.Properties["Required"]; diff --git a/src/NJsonSchema.Tests/Generation/JsonSchemaTypeAttributeTests.cs b/src/NJsonSchema.Tests/Generation/JsonSchemaTypeAttributeTests.cs index a039458cb..f6f48d387 100644 --- a/src/NJsonSchema.Tests/Generation/JsonSchemaTypeAttributeTests.cs +++ b/src/NJsonSchema.Tests/Generation/JsonSchemaTypeAttributeTests.cs @@ -24,7 +24,7 @@ public async Task When_type_of_primitive_properties_are_changed_then_the_schemas //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -55,7 +55,7 @@ public async Task When_type_of_array_properties_are_changed_then_the_schemas_are //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -93,7 +93,7 @@ public async Task When_type_of_complex_properties_are_changed_then_the_schemas_a //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -128,7 +128,7 @@ public async Task When_JsonSchemaTypeAttribute_is_on_class_then_property_defines //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs b/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs index b02e2f9e7..107db1c66 100644 --- a/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/KnownTypeGenerationTests.cs @@ -61,7 +61,7 @@ public async Task When_KnownType_attribute_exists_then_specified_classes_are_als //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert @@ -75,7 +75,7 @@ public async Task When_KnownType_attribute_includes_method_name_then_specified_c //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/NullPropertyTests.cs b/src/NJsonSchema.Tests/Generation/NullPropertyTests.cs index ebc7d1e18..2a884a4a8 100644 --- a/src/NJsonSchema.Tests/Generation/NullPropertyTests.cs +++ b/src/NJsonSchema.Tests/Generation/NullPropertyTests.cs @@ -19,7 +19,7 @@ public class ClassRoom public async Task When_property_is_nullable_then_property_schema_type_is_also_null() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); @@ -46,7 +46,7 @@ public class NotNullAttributeClass public async Task When_NotNullAttribute_is_available_then_property_is_not_nullable() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var json = schema.ToJson(); diff --git a/src/NJsonSchema.Tests/Generation/PrimitiveTypeGenerationTests.cs b/src/NJsonSchema.Tests/Generation/PrimitiveTypeGenerationTests.cs index b002fe099..27efa1721 100644 --- a/src/NJsonSchema.Tests/Generation/PrimitiveTypeGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/PrimitiveTypeGenerationTests.cs @@ -39,7 +39,7 @@ public async Task When_property_is_byte_array_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["Bytes"].Type); @@ -53,7 +53,7 @@ public async Task When_property_is_byte_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.Integer, schema.Properties["Byte"].Type); @@ -67,7 +67,7 @@ public async Task When_property_is_timespan_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["TimeSpan"].Type); @@ -81,7 +81,7 @@ public async Task When_property_is_type_then_schema_type_is_string() var data = JsonConvert.SerializeObject(new Foo { Type = typeof(Foo) }); // Type property is serialized as string //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); //// Assert @@ -95,7 +95,7 @@ public async Task When_property_is_localdate_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["Date"].Type); @@ -109,7 +109,7 @@ public async Task When_property_is_zoneddatetime_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["ZonedDateTime"].Type); @@ -123,7 +123,7 @@ public async Task When_property_is_offsetdatetime_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["OffsetDateTime"].Type); @@ -137,7 +137,7 @@ public async Task When_property_is_instant_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["Instant"].Type); @@ -151,7 +151,7 @@ public async Task When_property_is_duration_then_schema_type_is_string() //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["Duration"].Type); diff --git a/src/NJsonSchema.Tests/Generation/PropertyNamesGenerationTests.cs b/src/NJsonSchema.Tests/Generation/PropertyNamesGenerationTests.cs index 7cfb2bcf3..9efaa8810 100644 --- a/src/NJsonSchema.Tests/Generation/PropertyNamesGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/PropertyNamesGenerationTests.cs @@ -24,7 +24,7 @@ public async Task When_property_name_is_default_then_schema_has_reflected_names( //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultPropertyNameHandling = PropertyNameHandling.Default }); @@ -44,7 +44,7 @@ public async Task When_property_name_is_camel_then_schema_has_camel_names() //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultPropertyNameHandling = PropertyNameHandling.CamelCase }); @@ -64,7 +64,7 @@ public async Task When_property_name_is_snake_then_schema_has_snake_names() //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultPropertyNameHandling = PropertyNameHandling.SnakeCase }); diff --git a/src/NJsonSchema.Tests/Generation/SampleJsonSchemaGeneratorTests.cs b/src/NJsonSchema.Tests/Generation/SampleJsonSchemaGeneratorTests.cs index 1825ee140..1220ccd45 100644 --- a/src/NJsonSchema.Tests/Generation/SampleJsonSchemaGeneratorTests.cs +++ b/src/NJsonSchema.Tests/Generation/SampleJsonSchemaGeneratorTests.cs @@ -56,7 +56,7 @@ public void ComplexArrayProperty() }"; //// Act - var schema = JsonSchema4.FromSampleJson(data); + var schema = JsonSchema.FromSampleJson(data); var json = schema.ToJson(); var property = schema.Properties["persons"].ActualTypeSchema; @@ -94,7 +94,7 @@ public void MergedSchemas() }"; //// Act - var schema = JsonSchema4.FromSampleJson(data); + var schema = JsonSchema.FromSampleJson(data); var json = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Generation/SchemaGenerationTests.cs b/src/NJsonSchema.Tests/Generation/SchemaGenerationTests.cs index dd2f07bb9..ba38d1bd4 100644 --- a/src/NJsonSchema.Tests/Generation/SchemaGenerationTests.cs +++ b/src/NJsonSchema.Tests/Generation/SchemaGenerationTests.cs @@ -28,7 +28,7 @@ public async Task When_generating_schema_with_object_property_then_additional_pr //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert @@ -41,7 +41,7 @@ public async Task When_generating_DateTimeOffset_property_then_format_datetime_m //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert @@ -55,7 +55,7 @@ public async Task When_generating_schema_with_dictionary_property_then_it_must_a //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert @@ -70,7 +70,7 @@ public async Task When_output_schema_contains_reference_then_schema_reference_pa //// Arrange //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Assert @@ -87,7 +87,7 @@ public class DefaultTests public async Task When_default_value_is_set_on_property_then_default_is_set_in_schema() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Act var property = schema.Properties["Number"]; @@ -105,7 +105,7 @@ public class DictTest public async Task When_dictionary_value_is_null_then_string_values_are_allowed() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); var data = @"{ @@ -125,7 +125,7 @@ public async Task When_dictionary_value_is_null_then_string_values_are_allowed() public async Task When_type_is_enumerable_it_should_not_stackoverflow_on_JSON_generation() { //// Generate JSON - var schema = await JsonSchema4.FromTypeAsync>>(); + var schema = await JsonSchema.FromTypeAsync>>(); var json = schema.ToJson(); //// Should be reached and not StackOverflowed @@ -143,7 +143,7 @@ public class FilterDto public async Task When_property_is_object_then_it_should_not_be_a_dictonary_but_any() { /// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Assert @@ -163,7 +163,7 @@ public class ClassWithStaticProperty public async Task When_property_is_static_then_it_is_ignored() { /// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var json = schema.ToJson(); /// Assert diff --git a/src/NJsonSchema.Tests/Generation/SchemaProcessorTests.cs b/src/NJsonSchema.Tests/Generation/SchemaProcessorTests.cs index 436c2ffc1..6b13eb6c7 100644 --- a/src/NJsonSchema.Tests/Generation/SchemaProcessorTests.cs +++ b/src/NJsonSchema.Tests/Generation/SchemaProcessorTests.cs @@ -33,7 +33,7 @@ public class ClassWithSchemaProcessor public async Task When_class_has_schema_processor_attribute_then_it_is_processed() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); diff --git a/src/NJsonSchema.Tests/Generation/ShouldSerializeTests.cs b/src/NJsonSchema.Tests/Generation/ShouldSerializeTests.cs index 9fa5fbb8c..715ee2b1d 100644 --- a/src/NJsonSchema.Tests/Generation/ShouldSerializeTests.cs +++ b/src/NJsonSchema.Tests/Generation/ShouldSerializeTests.cs @@ -18,7 +18,7 @@ public bool ShouldSerializeName() public void When_ShouldSerialize_method_exists_then_schema_is_generated() { //// Arrange - var schema = JsonSchema4.FromTypeAsync(); + var schema = JsonSchema.FromTypeAsync(); //// Act diff --git a/src/NJsonSchema.Tests/Generation/TypeMapperTests.cs b/src/NJsonSchema.Tests/Generation/TypeMapperTests.cs index 9bb9f9af5..f9fb8622a 100644 --- a/src/NJsonSchema.Tests/Generation/TypeMapperTests.cs +++ b/src/NJsonSchema.Tests/Generation/TypeMapperTests.cs @@ -24,7 +24,7 @@ public class Bar public async Task When_primitive_type_mapping_is_available_for_type_then_it_is_called() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { TypeMappers = { @@ -44,18 +44,18 @@ public async Task When_primitive_type_mapping_is_available_for_type_then_it_is_c public async Task When_object_type_mapping_is_available_for_type_then_it_is_called() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { TypeMappers = { - new ObjectTypeMapper(typeof(Bar), new JsonSchema4 + new ObjectTypeMapper(typeof(Bar), new JsonSchema { Type = JsonObjectType.Object, Properties = { { "Prop", - new JsonProperty + new JsonSchemaProperty { IsRequired = true, Type = JsonObjectType.String @@ -102,7 +102,7 @@ public class MyTypeMapper : ITypeMapper public bool UseReference => true; - public async Task GenerateSchemaAsync(JsonSchema4 schema, TypeMapperContext context) + public async Task GenerateSchemaAsync(JsonSchema schema, TypeMapperContext context) { schema.Reference = await context.JsonSchemaGenerator.GenerateAsync(context.Type.GenericTypeArguments[0], context.JsonSchemaResolver); } @@ -112,7 +112,7 @@ public async Task GenerateSchemaAsync(JsonSchema4 schema, TypeMapperContext cont public async Task When_generic_type_mapper_is_defined_then_it_is_called_and_the_refs_are_correct() { //// Act - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { TypeMappers = { diff --git a/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs b/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs index 9397b241d..a4082fdb7 100644 --- a/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs +++ b/src/NJsonSchema.Tests/Generation/XmlObjectTests.cs @@ -93,7 +93,7 @@ public static string CreateTestArrayXml() [Fact] public async Task When_xmlobject_generation_is_active_with_a_type_without_xml_attributes() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings() { GenerateXmlObjects = true }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings() { GenerateXmlObjects = true }); //// Assert AssertTypeWithoutXmlAttributes(schema); @@ -155,7 +155,7 @@ public async Task When_xmlobject_generation_is_active_with_a_type_without_xml_at [Fact] public async Task When_xmlobject_generation_is_active_with_a_arraytype_as_parent_with_without_xml_attributes_defined() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings() { GenerateXmlObjects = true }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings() { GenerateXmlObjects = true }); var schemaData = schema.ToJson(); var schemaObject = JObject.Parse(schemaData); @@ -171,7 +171,7 @@ public async Task When_xmlobject_generation_is_active_with_a_arraytype_as_parent AssertTypeWithoutXmlAttributes(definitionSchema); } - private void AssertTypeWithoutXmlAttributes(JsonSchema4 schema) + private void AssertTypeWithoutXmlAttributes(JsonSchema schema) { Assert.Null(schema.Xml); var fooProperty = schema.Properties[Foo]; @@ -209,7 +209,7 @@ private void AssertTypeWithoutXmlAttributes(JsonSchema4 schema) [Fact] public async Task When_xmlobject_generation_is_active_with_a_type_without_xml_attributes_and_serialized() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings() { GenerateXmlObjects = true }); + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings() { GenerateXmlObjects = true }); var schemaData = schema.ToJson(); var schemaObject = JObject.Parse(schemaData); @@ -326,7 +326,7 @@ public static string CreateTestArrayXml() [Fact] public async Task When_xmlobject_generation_is_active_with_a_type_with_xml_attributes() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { GenerateXmlObjects = true }); @@ -389,7 +389,7 @@ public async Task When_xmlobject_generation_is_active_with_a_type_with_xml_attri [Fact] public async Task When_xmlobject_generation_is_active_with_a_arraytype_as_parent_with_xml_attributes_defined() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { GenerateXmlObjects = true }); @@ -410,7 +410,7 @@ public async Task When_xmlobject_generation_is_active_with_a_arraytype_as_parent AssertTypeWithXmlAttributes(schema, definitionSchema); } - private void AssertTypeWithXmlAttributes(JsonSchema4 schema, JsonSchema4 rootDefinitionSchema) + private void AssertTypeWithXmlAttributes(JsonSchema schema, JsonSchema rootDefinitionSchema) { Assert.Equal("NotTheSameName", rootDefinitionSchema.Xml.Name); Assert.Equal("http://test.shema.org/type", rootDefinitionSchema.Xml.Namespace); @@ -452,7 +452,7 @@ private void AssertTypeWithXmlAttributes(JsonSchema4 schema, JsonSchema4 rootDef [Fact] public async Task When_xmlobject_generation_is_active_with_a_type_with_xml_attributes_and_serialized() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { GenerateXmlObjects = true }); @@ -486,7 +486,7 @@ public class WithXmlIncorrectAttributesDefined [Fact] public async Task When_xmlobject_generation_is_active_with_a_type_with_xml_attributes_that_are_incorrect() { - var schema = await JsonSchema4.FromTypeAsync(new JsonSchemaGeneratorSettings + var schema = await JsonSchema.FromTypeAsync(new JsonSchemaGeneratorSettings { GenerateXmlObjects = true }); diff --git a/src/NJsonSchema.Tests/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolverTests.cs b/src/NJsonSchema.Tests/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolverTests.cs index 112be8b13..d05f83444 100644 --- a/src/NJsonSchema.Tests/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolverTests.cs +++ b/src/NJsonSchema.Tests/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolverTests.cs @@ -12,13 +12,13 @@ public void When_property_is_renamed_then_it_does_not_land_in_extension_data() { //// Arrange var resolver = new PropertyRenameAndIgnoreSerializerContractResolver(); - resolver.RenameProperty(typeof(JsonProperty), "x-readOnly", "readOnly"); - resolver.RenameProperty(typeof(JsonSchema4), "x-nullable", "nullable"); + resolver.RenameProperty(typeof(JsonSchemaProperty), "x-readOnly", "readOnly"); + resolver.RenameProperty(typeof(JsonSchema), "x-nullable", "nullable"); var json = "{ \"readOnly\": true, \"nullable\": true, \"additionalProperties\": { \"nullable\": true } }"; //// Act - var obj = JsonSchemaSerialization.FromJson(json, resolver); + var obj = JsonSchemaSerialization.FromJson(json, resolver); //// Assert Assert.True(obj.IsReadOnly); @@ -54,13 +54,13 @@ public void When_property_is_renamed_then_json_is_correct() public class ClassWithDoubleProperties { [JsonProperty("schema")] - public JsonSchema4 Schema { get; set; } + public JsonSchema Schema { get; set; } [JsonProperty("definitions1")] - public Dictionary Definitions1 => Definitions2; + public Dictionary Definitions1 => Definitions2; [JsonProperty("definitions2")] - public Dictionary Definitions2 { get; set; } = new Dictionary(); + public Dictionary Definitions2 { get; set; } = new Dictionary(); } [Fact] @@ -70,13 +70,13 @@ public void When_property_is_ignored_then_refs_ignore_it() var contractResolver = new PropertyRenameAndIgnoreSerializerContractResolver(); contractResolver.IgnoreProperty(typeof(ClassWithDoubleProperties), "definitions1"); - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.Object }; var foo = new ClassWithDoubleProperties { - Schema = new JsonSchema4 { Reference = schema }, + Schema = new JsonSchema { Reference = schema }, Definitions1 = { { "Bar", schema } diff --git a/src/NJsonSchema.Tests/References/LocalReferencesTests.cs b/src/NJsonSchema.Tests/References/LocalReferencesTests.cs index cea498dc6..1ee767520 100644 --- a/src/NJsonSchema.Tests/References/LocalReferencesTests.cs +++ b/src/NJsonSchema.Tests/References/LocalReferencesTests.cs @@ -31,7 +31,7 @@ public async Task When_definitions_is_nested_then_refs_work() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var j = schema.ToJson(); //// Assert @@ -45,7 +45,7 @@ public async Task When_schema_references_collection_in_definitions_it_works() var path = GetTestDirectory() + "/References/LocalReferencesTests/schema_with_collection_reference.json"; //// Act - var schema = await JsonSchema4.FromFileAsync(path); + var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert @@ -61,7 +61,7 @@ public async Task When_schema_references_external_schema_then_it_is_inlined_with var path = GetTestDirectory() + "/References/LocalReferencesTests/schema_with_reference.json"; //// Act - var schema = await JsonSchema4.FromFileAsync(path); + var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert @@ -76,7 +76,7 @@ public async Task When_document_has_indirect_external_ref_than_it_is_loaded() var path = GetTestDirectory() + "/References/LocalReferencesTests/schema_with_indirect_reference.json"; //// Act - var schema = await JsonSchema4.FromFileAsync(path); + var schema = await JsonSchema.FromFileAsync(path); var json = schema.ToJson(); //// Assert @@ -87,7 +87,7 @@ public async Task When_document_has_indirect_external_ref_than_it_is_loaded() public async Task When_reference_is_registered_in_custom_resolver_it_should_not_try_to_access_file() { //// Arrange - var externalSchema = await JsonSchema4.FromJsonAsync( + var externalSchema = await JsonSchema.FromJsonAsync( @"{ ""type"": ""object"", ""properties"": { @@ -97,7 +97,7 @@ public async Task When_reference_is_registered_in_custom_resolver_it_should_not_ } }"); - Func factory = schema4 => + Func factory = schema4 => { var schemaResolver = new JsonSchemaResolver(schema4, new JsonSchemaGeneratorSettings()); var resolver = new JsonReferenceResolver(schemaResolver); @@ -117,7 +117,7 @@ public async Task When_reference_is_registered_in_custom_resolver_it_should_not_ }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(schemaJson, ".", factory); + var schema = await JsonSchema.FromJsonAsync(schemaJson, ".", factory); //// Assert Assert.NotNull(schema); diff --git a/src/NJsonSchema.Tests/Schema/DataContractTests.cs b/src/NJsonSchema.Tests/Schema/DataContractTests.cs index e368d2e88..41dc3f704 100644 --- a/src/NJsonSchema.Tests/Schema/DataContractTests.cs +++ b/src/NJsonSchema.Tests/Schema/DataContractTests.cs @@ -17,7 +17,7 @@ public class MissingDataContract public async Task When_DataContractAttribute_is_missing_then_DataMember_is_ignored() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties.ContainsKey("Bar")); @@ -37,7 +37,7 @@ public class NotMissingDataContract public async Task When_DataContractAttribute_is_not_missing_then_DataMember_is_checked() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties.ContainsKey("bar")); @@ -56,7 +56,7 @@ public class DataContractWithoutDataMember public async Task When_class_has_DataContractAttribute_then_properties_without_DataMemberAttributes_are_ignored() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(0, schema.Properties.Count); @@ -74,7 +74,7 @@ public class DataContractWithoutDataMemberWithJsonProperty public async Task When_class_has_DataContractAttribute_then_property_without_DataMemberAttribute_and_with_JsonPropertyAttribute_is_not_ignored() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties.ContainsKey("bar")); @@ -93,7 +93,7 @@ public class DataContractWitDataMemberWithJsonProperty public async Task When_class_has_DataContractAttribute_then_property_with_DataMemberAttribute_and_JsonIgnoreAttribute_is_ignored() { //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(0, schema.Properties.Count); @@ -113,7 +113,7 @@ public async Task When_DataMemberAttribute_is_required_then_schema_property_is_r //var json = JsonConvert.DeserializeObject("{}"); //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.True(schema.Properties["req"].IsRequired); diff --git a/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetJsonPathTests.cs b/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetJsonPathTests.cs index adaccdf6e..8d39eafae 100644 --- a/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetJsonPathTests.cs +++ b/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetJsonPathTests.cs @@ -9,7 +9,7 @@ public class JsonPathUtilitiesGetJsonPathTests public void When_object_is_in_property_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); var obj = new { Property = new @@ -30,7 +30,7 @@ public void When_object_is_in_property_then_path_should_be_built_correctly() public void When_object_is_in_list_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); var obj = new { Property = new @@ -55,7 +55,7 @@ public void When_object_is_in_list_then_path_should_be_built_correctly() public void When_object_is_in_dictionary_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); var obj = new { Property = new @@ -80,7 +80,7 @@ public void When_object_is_in_dictionary_then_path_should_be_built_correctly() public void When_object_is_root_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); //// Act var path = JsonPathUtilities.GetJsonPath(objectToSearch, objectToSearch); diff --git a/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetObjectFromJsonPathTests.cs b/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetObjectFromJsonPathTests.cs index e89d45a30..0df21c0b8 100644 --- a/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetObjectFromJsonPathTests.cs +++ b/src/NJsonSchema.Tests/Schema/JsonPathUtilitiesGetObjectFromJsonPathTests.cs @@ -10,7 +10,7 @@ public class JsonPathUtilitiesGetObjectFromJsonPathTests public async Task When_object_is_in_property_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); var obj = new { Property = new @@ -32,7 +32,7 @@ public async Task When_object_is_in_property_then_path_should_be_built_correctly public async Task When_object_is_in_list_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); var obj = new { Property = new @@ -58,7 +58,7 @@ public async Task When_object_is_in_list_then_path_should_be_built_correctly() public async Task When_object_is_in_dictionary_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); var obj = new { Property = new @@ -84,7 +84,7 @@ public async Task When_object_is_in_dictionary_then_path_should_be_built_correct public async Task When_object_is_root_then_path_should_be_built_correctly() { //// Arrange - var objectToSearch = new JsonSchema4(); + var objectToSearch = new JsonSchema(); //// Act var resolver = new JsonReferenceResolver(null); diff --git a/src/NJsonSchema.Tests/Schema/JsonSchemaTests.cs b/src/NJsonSchema.Tests/Schema/JsonSchemaTests.cs index 352030224..6218c2db1 100644 --- a/src/NJsonSchema.Tests/Schema/JsonSchemaTests.cs +++ b/src/NJsonSchema.Tests/Schema/JsonSchemaTests.cs @@ -11,14 +11,14 @@ public class JsonSchemaTests [Fact] public async Task Ensure_NJS_does_not_run_in_legacy_mode() { - Assert.DoesNotContain("NET40", JsonSchema4.ToolchainVersion); + Assert.DoesNotContain("NET40", JsonSchema.ToolchainVersion); } [Fact] public void When_creating_schema_without_setting_properties_then_it_is_empty() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); //// Act var data = schema.ToJson(); @@ -73,7 +73,7 @@ public async Task When_schema_contains_refs_then_they_should_be_resolved() "; //// Act - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); //// Assert Assert.NotNull(schema.Definitions["diskDevice"]); @@ -105,7 +105,7 @@ public async Task When_deserializing_schema_then_it_should_be_read_correctly() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); var x = schema.ToJson(); //// Assert @@ -126,7 +126,7 @@ public async Task When_deserializing_multiple_types_then_flags_should_be_set_cor }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); //// Assert Assert.True(schema.Type.HasFlag(JsonObjectType.String)); @@ -143,7 +143,7 @@ public async Task When_deserializing_single_type_then_flags_should_be_set_correc }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); //// Assert Assert.True(schema.Type.HasFlag(JsonObjectType.String)); @@ -160,7 +160,7 @@ public async Task When_deserializing_schema_it_should_not_stackoverflow() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(data); + var schema = await JsonSchema.FromJsonAsync(data); var x = schema.ToJson(); //// Assert @@ -171,7 +171,7 @@ public async Task When_deserializing_schema_it_should_not_stackoverflow() public void When_setting_single_type_then_it_should_be_serialized_correctly() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); //// Act schema.Type = JsonObjectType.Integer; @@ -185,7 +185,7 @@ public void When_setting_single_type_then_it_should_be_serialized_correctly() public void When_setting_multiple_type_then_it_should_be_serialized_correctly() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); //// Act schema.Type = JsonObjectType.Integer | JsonObjectType.Object; @@ -202,10 +202,10 @@ public void When_setting_multiple_type_then_it_should_be_serialized_correctly() public void When_adding_property_to_schema_then_parent_should_be_set() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); //// Act - schema.Properties.Add("test", new JsonProperty()); + schema.Properties.Add("test", new JsonSchemaProperty()); //// Assert Assert.True(schema.Properties.ContainsKey("test")); @@ -216,8 +216,8 @@ public void When_adding_property_to_schema_then_parent_should_be_set() public void When_setting_property_required_then_the_key_should_be_added() { //// Arrange - var schema = new JsonSchema4(); - schema.Properties["test"] = new JsonProperty(); + var schema = new JsonSchema(); + schema.Properties["test"] = new JsonSchemaProperty(); //// Act schema.Properties["test"].IsRequired = true; @@ -230,8 +230,8 @@ public void When_setting_property_required_then_the_key_should_be_added() public void When_setting_property_not_required_then_the_key_should_be_added() { //// Arrange - var schema = new JsonSchema4(); - schema.Properties["test"] = new JsonProperty(); + var schema = new JsonSchema(); + schema.Properties["test"] = new JsonSchemaProperty(); schema.RequiredProperties.Add("test"); //// Act @@ -245,8 +245,8 @@ public void When_setting_property_not_required_then_the_key_should_be_added() public void When_number_property_is_null_and_not_required_then_it_is_invalid() { //// Arrange - var schema = new JsonSchema4(); - schema.Properties["test"] = new JsonProperty + var schema = new JsonSchema(); + schema.Properties["test"] = new JsonSchemaProperty { Type = JsonObjectType.Number, IsRequired = false @@ -263,9 +263,9 @@ public void When_number_property_is_null_and_not_required_then_it_is_invalid() public void When_property_matches_one_of_the_types_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty + schema.Properties["Foo"] = new JsonSchemaProperty { Type = JsonObjectType.Number | JsonObjectType.Null }; @@ -284,10 +284,10 @@ public void When_property_matches_one_of_the_types_then_it_should_succeed() public void When_property_type_not_specified_then_anything_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty(); - schema.Properties["Bar"] = new JsonProperty(); + schema.Properties["Foo"] = new JsonSchemaProperty(); + schema.Properties["Bar"] = new JsonSchemaProperty(); var token = new JObject(); token["Foo"] = new JValue(5); @@ -303,7 +303,7 @@ public void When_property_type_not_specified_then_anything_should_succeed() public void When_DateTimeOffset_is_validated_then_it_should_not_throw() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String }; @@ -338,7 +338,7 @@ public async Task When_schema_has_cyclic_references_then_exception_is_thrown() await Assert.ThrowsAsync(async () => { //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var data = schema.ToJson(); //// Assert @@ -374,7 +374,7 @@ public async Task When_schema_is_loaded_then_all_refs_are_resolved() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var data = schema.ToJson(); //// Assert @@ -390,7 +390,7 @@ public async Task When_json_schema_is_loaded_then_no_collection_modified_excepti //// Act - var schema = await JsonSchema4.FromUrlAsync("http://schemas.sportradar.com/bsa/json/v1/endpoints/soccer/team_profile.json"); + var schema = await JsonSchema.FromUrlAsync("http://schemas.sportradar.com/bsa/json/v1/endpoints/soccer/team_profile.json"); var json = schema.ToJson(); //// Assert @@ -406,7 +406,7 @@ public async Task When_schema_has_metadata_properties_it_can_still_be_read() ""format"": ""guid"" }, ""Name"": { ""type"": ""string"" } }, ""required"": [ ""$type"", ""Id"", ""Name"" ] }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Assert // No exception diff --git a/src/NJsonSchema.Tests/Serialization/DiscriminatorSerializationTests.cs b/src/NJsonSchema.Tests/Serialization/DiscriminatorSerializationTests.cs index 9c04619a2..25fa0e4d7 100644 --- a/src/NJsonSchema.Tests/Serialization/DiscriminatorSerializationTests.cs +++ b/src/NJsonSchema.Tests/Serialization/DiscriminatorSerializationTests.cs @@ -12,12 +12,12 @@ public class DiscriminatorSerializationTests public async Task When_discriminator_object_is_set_then_schema_is_correctly_serialized() { //// Arrange - var childSchema = new JsonSchema4 + var childSchema = new JsonSchema { Type = JsonObjectType.Object, }; - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Definitions["Foo"] = childSchema; schema.DiscriminatorObject = new OpenApiDiscriminator { @@ -26,7 +26,7 @@ public async Task When_discriminator_object_is_set_then_schema_is_correctly_seri { { "Bar", - new JsonSchema4 + new JsonSchema { Reference = childSchema } @@ -36,7 +36,7 @@ public async Task When_discriminator_object_is_set_then_schema_is_correctly_seri //// Act var json = schema.ToJson(); - var schema2 = await JsonSchema4.FromJsonAsync(json); + var schema2 = await JsonSchema.FromJsonAsync(json); var json2 = schema2.ToJson(); //// Assert @@ -52,7 +52,7 @@ public async Task When_discriminator_object_is_set_then_schema_is_correctly_seri public void When_discriminator_is_set_then_discriminator_object_is_created() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Discriminator = "discr"; //// Act @@ -66,12 +66,12 @@ public void When_discriminator_is_set_then_discriminator_object_is_created() public void When_schema_is_serialized_for_Swagger_then_discriminator_is_string() { //// Arrange - var childSchema = new JsonSchema4 + var childSchema = new JsonSchema { Type = JsonObjectType.Object, }; - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Definitions["Foo"] = childSchema; schema.DiscriminatorObject = new OpenApiDiscriminator { @@ -80,7 +80,7 @@ public void When_schema_is_serialized_for_Swagger_then_discriminator_is_string() { { "Bar", - new JsonSchema4 + new JsonSchema { Reference = childSchema } diff --git a/src/NJsonSchema.Tests/Serialization/ExtensionDataTests.cs b/src/NJsonSchema.Tests/Serialization/ExtensionDataTests.cs index fde706854..d632ff44c 100644 --- a/src/NJsonSchema.Tests/Serialization/ExtensionDataTests.cs +++ b/src/NJsonSchema.Tests/Serialization/ExtensionDataTests.cs @@ -14,7 +14,7 @@ public async Task When_definition_entry_is_null_then_it_is_deserialized_correctl var json = @"{ ""definitions"": { ""abc"": null } }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var json2 = schema.ToJson(); //// Assert @@ -26,7 +26,7 @@ public async Task When_definition_entry_is_null_then_it_is_deserialized_correctl public void When_schema_has_extension_data_property_then_property_is_in_serialized_json() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.ExtensionData = new Dictionary { { "Test", 123 } @@ -53,7 +53,7 @@ public async Task When_json_schema_contains_unknown_data_then_extension_data_is_ }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Assert Assert.Equal((long)123, schema.ExtensionData["Test"]); @@ -69,7 +69,7 @@ public async Task When_no_extension_data_is_available_then_property_is_null() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Assert Assert.Null(schema.ExtensionData); @@ -90,7 +90,7 @@ public async Task When_extension_data_attribute_is_used_on_class_then_extension_ //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(123, schema.ExtensionData["MyClass"]); @@ -103,7 +103,7 @@ public async Task When_extension_data_attribute_is_used_on_property_then_extensi //// Act - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); //// Assert Assert.Equal(2, schema.Properties["Property"].ExtensionData["Foo"]); @@ -165,7 +165,7 @@ public async Task When_reference_references_schema_in_custom_properties_then_the }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); var json2 = schema.ToJson(); //// Assert diff --git a/src/NJsonSchema.Tests/Validation/ArrayValidationTests.cs b/src/NJsonSchema.Tests/Validation/ArrayValidationTests.cs index c0b09592a..86abd469c 100644 --- a/src/NJsonSchema.Tests/Validation/ArrayValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/ArrayValidationTests.cs @@ -12,7 +12,7 @@ public class ArrayValidationTests public async Task When_json_is_array_then_validate_should_not_throw_an_exception() { //// Act - var svc = await JsonSchema4.FromJsonAsync(@"{ ""type"": ""array"", ""items"": { ""type"":""string"" } }"); + var svc = await JsonSchema.FromJsonAsync(@"{ ""type"": ""array"", ""items"": { ""type"":""string"" } }"); //// Assert Assert.Equal(0, svc.Validate(JToken.Parse("[]")).Count); @@ -30,7 +30,7 @@ public async Task When_type_is_array_and_items_and_item_is_not_defined_then_any_ 'emptySchema': { 'type': 'array' } } }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var errors1 = schema.Validate("{ 'emptySchema': [1, 2, 'abc'] }"); @@ -45,7 +45,7 @@ public async Task When_type_is_array_and_items_and_item_is_not_defined_then_any_ public void When_token_is_not_array_then_validation_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; var token = new JValue(10); @@ -62,10 +62,10 @@ public void When_token_is_not_array_then_validation_should_fail() public void When_tuple_correct_then_it_should_pass() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; - schema.Items.Add(new JsonSchema4 { Type = JsonObjectType.String }); - schema.Items.Add(new JsonSchema4 { Type = JsonObjectType.Integer }); + schema.Items.Add(new JsonSchema { Type = JsonObjectType.String }); + schema.Items.Add(new JsonSchema { Type = JsonObjectType.Integer }); var token = new JArray(); token.Add(new JValue("Foo")); @@ -82,10 +82,10 @@ public void When_tuple_correct_then_it_should_pass() public void When_tuple_too_large_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; - schema.Items.Add(new JsonSchema4 { Type = JsonObjectType.String }); - schema.Items.Add(new JsonSchema4 { Type = JsonObjectType.Integer }); + schema.Items.Add(new JsonSchema { Type = JsonObjectType.String }); + schema.Items.Add(new JsonSchema { Type = JsonObjectType.Integer }); schema.AllowAdditionalItems = false; var token = new JArray(); @@ -106,9 +106,9 @@ public void When_tuple_too_large_then_it_should_fail() public void When_array_item_are_valid_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; - schema.Item = new JsonSchema4(); + schema.Item = new JsonSchema(); schema.Item.Type = JsonObjectType.String; var token = new JArray(); @@ -126,9 +126,9 @@ public void When_array_item_are_valid_then_it_should_succeed() public void When_second_item_validation_fails_then_path_should_be_correct() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; - schema.Item = new JsonSchema4(); + schema.Item = new JsonSchema(); schema.Item.Type = JsonObjectType.String; var token = new JArray(); @@ -153,10 +153,10 @@ public void When_second_item_validation_fails_then_path_should_be_correct() public void When_max_item_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; schema.MaxItems = 1; - schema.Item = new JsonSchema4(); + schema.Item = new JsonSchema(); schema.Item.Type = JsonObjectType.String; var token = new JArray(); @@ -176,10 +176,10 @@ public void When_max_item_does_not_match_then_it_should_fail() public void When_min_items_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; schema.MinItems = 2; - schema.Item = new JsonSchema4(); + schema.Item = new JsonSchema(); schema.Item.Type = JsonObjectType.String; var token = new JArray(); @@ -198,10 +198,10 @@ public void When_min_items_does_not_match_then_it_should_fail() public void When_unique_items_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Array; schema.UniqueItems = true; - schema.Item = new JsonSchema4(); + schema.Item = new JsonSchema(); schema.Item.Type = JsonObjectType.String; var token = new JArray(); @@ -233,7 +233,7 @@ public async Task When_null_is_allowed_then_properties_are_not_checked() ""additionalProperties"": false } }"; - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); //// Act var errors = schema.Validate("[{\"value\":2},null]"); diff --git a/src/NJsonSchema.Tests/Validation/EnumValidationTests.cs b/src/NJsonSchema.Tests/Validation/EnumValidationTests.cs index 121762fe7..b51db0eee 100644 --- a/src/NJsonSchema.Tests/Validation/EnumValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/EnumValidationTests.cs @@ -16,7 +16,7 @@ public async Task When_enum_is_defined_without_type_then_validation_succeeds_for ""residential"" ] }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var errors = schema.Validate(@"""commercial"""); @@ -36,7 +36,7 @@ public async Task When_enum_is_defined_without_type_then_validation_fails_for_wr ""residential"" ] }"; - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var errors = schema.Validate(@"""wrong"""); @@ -69,7 +69,7 @@ public async Task When_enumeration_has_null_then_validation_works() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var errors = schema.Validate(@"{ ""SalutationType"": ""Prof"" }"); @@ -102,7 +102,7 @@ public async Task When_enumeration_has_null_and_value_is_null_then_no_validation }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var errors = schema.Validate(@"{ ""SalutationType"": null }"); @@ -134,7 +134,7 @@ public async Task When_enumeration_doesnt_have_null_and_value_is_null_then_valid }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(json); + var schema = await JsonSchema.FromJsonAsync(json); //// Act var errors = schema.Validate(@"{ ""SalutationType"": null }"); diff --git a/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs b/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs index 765fd8e06..78976a636 100644 --- a/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatBase64Tests.cs @@ -12,7 +12,7 @@ public class FormatBase64Tests public void Validation_should_fail_if_string_is_not_base64_formatted() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String, Format = "base64" @@ -32,7 +32,7 @@ public void Validation_should_fail_if_string_is_not_base64_formatted() public void Validation_should_fail_if_string_is_not_byte_formatted() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String, Format = JsonFormatStrings.Byte @@ -52,7 +52,7 @@ public void Validation_should_fail_if_string_is_not_byte_formatted() public void Validation_should_succeed_if_string_is_base64_formatted_with_trailing_equals() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String, Format = "base64" @@ -72,7 +72,7 @@ public void Validation_should_succeed_if_string_is_base64_formatted_with_trailin public void Validation_should_succeed_if_string_is_byte_formatted_with_trailing_equals() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String, Format = JsonFormatStrings.Byte @@ -92,7 +92,7 @@ public void Validation_should_succeed_if_string_is_byte_formatted_with_trailing_ public void Validation_should_succeed_if_string_is_base64_formatted_without_trailing_equals() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String, Format = "base64" @@ -112,7 +112,7 @@ public void Validation_should_succeed_if_string_is_base64_formatted_without_trai public void Validation_should_succeed_if_string_is_byte_formatted_without_trailing_equals() { //// Arrange - var schema = new JsonSchema4 + var schema = new JsonSchema { Type = JsonObjectType.String, Format = JsonFormatStrings.Byte @@ -132,7 +132,7 @@ public void Validation_should_succeed_if_string_is_byte_formatted_without_traili public void Numeric_type_should_not_trigger_validation_if_has_byte_format() { //// Arrange - var numericSchema = new JsonSchema4 + var numericSchema = new JsonSchema { Type = JsonObjectType.Integer, Format = JsonFormatStrings.Byte diff --git a/src/NJsonSchema.Tests/Validation/FormatDateTests.cs b/src/NJsonSchema.Tests/Validation/FormatDateTests.cs index 711f01bf0..b7d7586ae 100644 --- a/src/NJsonSchema.Tests/Validation/FormatDateTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatDateTests.cs @@ -11,7 +11,7 @@ public class FormatDateTests public void When_format_date_incorrect_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Date; @@ -28,7 +28,7 @@ public void When_format_date_incorrect_then_validation_fails() public void When_format_date_time_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Date; @@ -45,7 +45,7 @@ public void When_format_date_time_then_validation_fails() public void When_format_date_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Date; diff --git a/src/NJsonSchema.Tests/Validation/FormatDateTimeTests.cs b/src/NJsonSchema.Tests/Validation/FormatDateTimeTests.cs index 2bfe7676a..a8377c38e 100644 --- a/src/NJsonSchema.Tests/Validation/FormatDateTimeTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatDateTimeTests.cs @@ -11,7 +11,7 @@ public class FormatDateTimeTests public void When_format_date_time_incorrect_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.DateTime; @@ -28,7 +28,7 @@ public void When_format_date_time_incorrect_then_validation_succeeds() public void When_format_date_time_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.DateTime; @@ -45,7 +45,7 @@ public void When_format_date_time_correct_then_validation_succeeds() public void When_format_date_time_with_non_iso8601_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.DateTime; @@ -62,7 +62,7 @@ public void When_format_date_time_with_non_iso8601_then_validation_succeeds() public void When_format_date_time_with_iso8601_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.DateTime; @@ -79,7 +79,7 @@ public void When_format_date_time_with_iso8601_then_validation_succeeds() public void When_format_date_time_with_iso8601_with_timezone_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.DateTime; @@ -96,7 +96,7 @@ public void When_format_date_time_with_iso8601_with_timezone_then_validation_suc public void When_format_date_time_with_iso8601_and_fractional_seconds_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.DateTime; diff --git a/src/NJsonSchema.Tests/Validation/FormatEmailTests.cs b/src/NJsonSchema.Tests/Validation/FormatEmailTests.cs index 5873e9b79..1152a2976 100644 --- a/src/NJsonSchema.Tests/Validation/FormatEmailTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatEmailTests.cs @@ -11,7 +11,7 @@ public class FormatEmailTests public void When_format_email_incorrect_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Email; @@ -28,7 +28,7 @@ public void When_format_email_incorrect_then_validation_succeeds() public void When_format_email_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Email; diff --git a/src/NJsonSchema.Tests/Validation/FormatGuidTests.cs b/src/NJsonSchema.Tests/Validation/FormatGuidTests.cs index cdd2f9a1e..8e9067c2a 100644 --- a/src/NJsonSchema.Tests/Validation/FormatGuidTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatGuidTests.cs @@ -12,7 +12,7 @@ public class FormatGuidTests public void When_format_guid_incorrect_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Guid; @@ -29,7 +29,7 @@ public void When_format_guid_incorrect_then_validation_succeeds() public void When_format_guid_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Guid; diff --git a/src/NJsonSchema.Tests/Validation/FormatHostnameTests.cs b/src/NJsonSchema.Tests/Validation/FormatHostnameTests.cs index 11d52587e..ec2bf8301 100644 --- a/src/NJsonSchema.Tests/Validation/FormatHostnameTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatHostnameTests.cs @@ -11,7 +11,7 @@ public class FormatHostnameTests public void When_format_hostname_incorrect_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Hostname; @@ -28,7 +28,7 @@ public void When_format_hostname_incorrect_then_validation_succeeds() public void When_format_hostname_is_ip_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Hostname; diff --git a/src/NJsonSchema.Tests/Validation/FormatIpV4Tests.cs b/src/NJsonSchema.Tests/Validation/FormatIpV4Tests.cs index f6d3879b9..c3070d032 100644 --- a/src/NJsonSchema.Tests/Validation/FormatIpV4Tests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatIpV4Tests.cs @@ -11,7 +11,7 @@ public class FormatIpV4Tests public void When_format_ipv4_incorrect_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.IpV4; @@ -28,7 +28,7 @@ public void When_format_ipv4_incorrect_then_validation_succeeds() public void When_format_ipv4_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.IpV4; diff --git a/src/NJsonSchema.Tests/Validation/FormatIpV6Tests.cs b/src/NJsonSchema.Tests/Validation/FormatIpV6Tests.cs index bdcf4d3e4..f143ab13e 100644 --- a/src/NJsonSchema.Tests/Validation/FormatIpV6Tests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatIpV6Tests.cs @@ -11,7 +11,7 @@ public class FormatIpV6Tests public void When_format_ipv6_incorrect_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.IpV6; @@ -28,7 +28,7 @@ public void When_format_ipv6_incorrect_then_validation_fails() public void When_format_ipv6_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.IpV6; diff --git a/src/NJsonSchema.Tests/Validation/FormatTimeSpanTests.cs b/src/NJsonSchema.Tests/Validation/FormatTimeSpanTests.cs index 537b606a6..c6e1d43f4 100644 --- a/src/NJsonSchema.Tests/Validation/FormatTimeSpanTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatTimeSpanTests.cs @@ -11,7 +11,7 @@ public class FormatTimeSpanTests public void When_format_time_span_incorrect_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.TimeSpan; @@ -28,7 +28,7 @@ public void When_format_time_span_incorrect_then_validation_fails() public void When_format_time_span_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.TimeSpan; diff --git a/src/NJsonSchema.Tests/Validation/FormatTimeTests.cs b/src/NJsonSchema.Tests/Validation/FormatTimeTests.cs index 7a58b5be8..3e5c38412 100644 --- a/src/NJsonSchema.Tests/Validation/FormatTimeTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatTimeTests.cs @@ -15,7 +15,7 @@ public class FormatTimeTests public void When_format_time_incorrect_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Time; @@ -32,7 +32,7 @@ public void When_format_time_incorrect_then_validation_fails() public void When_format_time_positive_offset_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Time; @@ -49,7 +49,7 @@ public void When_format_time_positive_offset_then_validation_succeeds() public void When_format_time_has_negative_offset_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Time; @@ -66,7 +66,7 @@ public void When_format_time_has_negative_offset_succeeds() public void When_format_time_is_utc_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Time; @@ -83,7 +83,7 @@ public void When_format_time_is_utc_then_validation_succeeds() public void When_format_time_secfrac_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Time; @@ -104,7 +104,7 @@ public void When_format_time_secfrac_correct_then_validation_succeeds() public void When_format_time_is_not_utc_or_offset_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Time; diff --git a/src/NJsonSchema.Tests/Validation/FormatUriTests.cs b/src/NJsonSchema.Tests/Validation/FormatUriTests.cs index 8dfad3b42..b3e056905 100644 --- a/src/NJsonSchema.Tests/Validation/FormatUriTests.cs +++ b/src/NJsonSchema.Tests/Validation/FormatUriTests.cs @@ -11,7 +11,7 @@ public class FormatUriTests public void When_format_uri_incorrect_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Uri; @@ -28,7 +28,7 @@ public void When_format_uri_incorrect_then_validation_succeeds() public void When_format_uri_correct_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Format = JsonFormatStrings.Uri; diff --git a/src/NJsonSchema.Tests/Validation/InheritanceTests.cs b/src/NJsonSchema.Tests/Validation/InheritanceTests.cs index a889e1a3c..decc4ecee 100644 --- a/src/NJsonSchema.Tests/Validation/InheritanceTests.cs +++ b/src/NJsonSchema.Tests/Validation/InheritanceTests.cs @@ -11,12 +11,12 @@ public class InheritanceTests public void When_is_any_of_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); - schema.AnyOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.AnyOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.AnyOf.Add(new JsonSchema4 + schema.AnyOf.Add(new JsonSchema { Type = JsonObjectType.Integer }); @@ -34,12 +34,12 @@ public void When_is_any_of_then_it_should_succeed() public void When_is_not_any_of_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); - schema.AnyOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.AnyOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.AnyOf.Add(new JsonSchema4 + schema.AnyOf.Add(new JsonSchema { Type = JsonObjectType.Integer }); @@ -61,12 +61,12 @@ public void When_is_not_any_of_then_it_should_fail() public void When_is_all_of_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); - schema.AnyOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.AnyOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.AnyOf.Add(new JsonSchema4 + schema.AnyOf.Add(new JsonSchema { Type = JsonObjectType.String }); @@ -84,12 +84,12 @@ public void When_is_all_of_then_it_should_succeed() public void When_is_not_all_of_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); - schema.AllOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.AllOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.AllOf.Add(new JsonSchema4 + schema.AllOf.Add(new JsonSchema { Type = JsonObjectType.Integer }); @@ -108,12 +108,12 @@ public void When_is_not_all_of_then_it_should_fail() public void When_is_one_of_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); - schema.OneOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.OneOf.Add(new JsonSchema4 + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.Integer }); @@ -131,12 +131,12 @@ public void When_is_one_of_then_it_should_succeed() public void When_is_not_one_of_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); - schema.OneOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.OneOf.Add(new JsonSchema4 + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.Boolean }); @@ -155,16 +155,16 @@ public void When_is_not_one_of_then_it_should_fail() public void When_one_of_matches_multiple_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); - schema.OneOf.Add(new JsonSchema4 + var schema = new JsonSchema(); + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.String }); - schema.OneOf.Add(new JsonSchema4 + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.Integer }); - schema.OneOf.Add(new JsonSchema4 + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.Integer }); @@ -183,8 +183,8 @@ public void When_one_of_matches_multiple_then_it_should_fail() public void When_matches_excluded_schema_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); - schema.Not = new JsonSchema4 + var schema = new JsonSchema(); + schema.Not = new JsonSchema { Type = JsonObjectType.String }; @@ -203,8 +203,8 @@ public void When_matches_excluded_schema_then_it_should_fail() public void When_not_matches_excluded_schema_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); - schema.Not = new JsonSchema4 + var schema = new JsonSchema(); + schema.Not = new JsonSchema { Type = JsonObjectType.String }; diff --git a/src/NJsonSchema.Tests/Validation/LineInformationTest.cs b/src/NJsonSchema.Tests/Validation/LineInformationTest.cs index 4ba97ae55..20805e10e 100644 --- a/src/NJsonSchema.Tests/Validation/LineInformationTest.cs +++ b/src/NJsonSchema.Tests/Validation/LineInformationTest.cs @@ -11,13 +11,13 @@ namespace NJsonSchema.Tests.Validation { public class LineInformationTest { - private JsonSchema4 Schema { get; set; } + private JsonSchema Schema { get; set; } private string Json { get; set; } public async Task InitAsync() { - Schema = await JsonSchema4.FromJsonAsync(@"{ + Schema = await JsonSchema.FromJsonAsync(@"{ ""type"": ""object"", ""required"": [""prop1"", ""prop3""], ""additionalProperties"": false, diff --git a/src/NJsonSchema.Tests/Validation/NullPropertyTests.cs b/src/NJsonSchema.Tests/Validation/NullPropertyTests.cs index abc60cd37..54a144b21 100644 --- a/src/NJsonSchema.Tests/Validation/NullPropertyTests.cs +++ b/src/NJsonSchema.Tests/Validation/NullPropertyTests.cs @@ -9,12 +9,12 @@ public class NullPropertyTests public void When_property_can_be_null_then_null_is_allowed() { //// Arrange - var schema = new JsonSchema4(); - schema.Properties["test"] = new JsonProperty + var schema = new JsonSchema(); + schema.Properties["test"] = new JsonSchemaProperty { Type = JsonObjectType.Null | JsonObjectType.Object }; - schema.Properties["test"].Properties["foo"] = new JsonProperty + schema.Properties["test"].Properties["foo"] = new JsonSchemaProperty { Type = JsonObjectType.String }; @@ -41,7 +41,7 @@ public class QueryRule public async Task When_property_can_be_null_then_null_is_allowed2() { //// Arrange - var schema = await JsonSchema4.FromTypeAsync(); + var schema = await JsonSchema.FromTypeAsync(); var schemaData = schema.ToJson(); //// Act diff --git a/src/NJsonSchema.Tests/Validation/NumberTests.cs b/src/NJsonSchema.Tests/Validation/NumberTests.cs index f0ef36a3d..3012ea567 100644 --- a/src/NJsonSchema.Tests/Validation/NumberTests.cs +++ b/src/NJsonSchema.Tests/Validation/NumberTests.cs @@ -29,7 +29,7 @@ public async Task When_double_is_bigger_then_decimal_then_validation_works() 'UpperLimit': 1.1111111111111111E+101 }"; - var validationSchema = JsonSchema4.FromJsonAsync(json).Result; + var validationSchema = JsonSchema.FromJsonAsync(json).Result; /// Act var errors = validationSchema.Validate(data); @@ -60,7 +60,7 @@ public async Task When_integer_is_big_integer_then_validation_works() ""property1"": 34545734242323232423434 }"; - var validationSchema = JsonSchema4.FromJsonAsync(json).Result; + var validationSchema = JsonSchema.FromJsonAsync(json).Result; /// Act var errors = validationSchema.Validate(data); diff --git a/src/NJsonSchema.Tests/Validation/ObjectValidationTests.cs b/src/NJsonSchema.Tests/Validation/ObjectValidationTests.cs index 88c8d5581..4b106dbd8 100644 --- a/src/NJsonSchema.Tests/Validation/ObjectValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/ObjectValidationTests.cs @@ -12,9 +12,9 @@ public class ObjectValidationTests public void When_token_is_not_object_then_validation_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty(); + schema.Properties["Foo"] = new JsonSchemaProperty(); var token = new JValue(10); @@ -29,9 +29,9 @@ public void When_token_is_not_object_then_validation_should_fail() public void When_required_property_is_missing_then_it_should_be_in_error_list() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty + schema.Properties["Foo"] = new JsonSchemaProperty { IsRequired = true, }; @@ -52,9 +52,9 @@ public void When_required_property_is_missing_then_it_should_be_in_error_list() public void When_property_matches_one_of_the_types_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty + schema.Properties["Foo"] = new JsonSchemaProperty { Type = JsonObjectType.Number | JsonObjectType.Null }; @@ -73,9 +73,9 @@ public void When_property_matches_one_of_the_types_then_it_should_succeed() public void When_optional_property_is_missing_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty + schema.Properties["Foo"] = new JsonSchemaProperty { IsRequired = false, }; @@ -93,9 +93,9 @@ public void When_optional_property_is_missing_then_it_should_succeed() public void When_string_property_is_available_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty + schema.Properties["Foo"] = new JsonSchemaProperty { IsRequired = true, Type = JsonObjectType.String @@ -115,9 +115,9 @@ public void When_string_property_is_available_then_it_should_succeed() public void When_string_property_required_but_integer_provided_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; - schema.Properties["Foo"] = new JsonProperty + schema.Properties["Foo"] = new JsonSchemaProperty { IsRequired = true, Type = JsonObjectType.String @@ -139,7 +139,7 @@ public void When_string_property_required_but_integer_provided_then_it_should_fa public async Task When_type_property_has_integer_type_then_it_is_validated_correctly() { //// Arrange - var schema = await JsonSchema4.FromJsonAsync( + var schema = await JsonSchema.FromJsonAsync( @"{ ""$schema"": ""http://json-schema.org/draft-06/schema#"", ""type"": ""object"", diff --git a/src/NJsonSchema.Tests/Validation/OneOfValidationTests.cs b/src/NJsonSchema.Tests/Validation/OneOfValidationTests.cs index b54aac012..436fee9ec 100644 --- a/src/NJsonSchema.Tests/Validation/OneOfValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/OneOfValidationTests.cs @@ -27,7 +27,7 @@ public class OneOfValidationTests [Fact] public async Task When_has_one_of_then_it_is_validated_correctly() { - var schema = await JsonSchema4.FromJsonAsync(example_schema); + var schema = await JsonSchema.FromJsonAsync(example_schema); var matches = new string[] { @"{ ""A"": ""string"", ""B"": 3 }", @"{ ""A"": ""string"", ""C"": 2 }" }; @@ -42,7 +42,7 @@ public async Task When_has_one_of_then_it_is_validated_correctly() [Fact] public async Task When_does_not_have_one_of_then_it_is_invalid() { - var schema = await JsonSchema4.FromJsonAsync(example_schema); + var schema = await JsonSchema.FromJsonAsync(example_schema); var errors = schema.Validate(@"{ ""A"": ""string"" }"); @@ -52,7 +52,7 @@ public async Task When_does_not_have_one_of_then_it_is_invalid() [Fact] public async Task When_has_more_than_one_of_then_it_is_invalid() { - var schema = await JsonSchema4.FromJsonAsync(example_schema); + var schema = await JsonSchema.FromJsonAsync(example_schema); var errors = schema.Validate(@"{ ""A"": ""string"", ""B"": 1, ""C"": 2 }"); diff --git a/src/NJsonSchema.Tests/Validation/PatternPropertyValidationTests.cs b/src/NJsonSchema.Tests/Validation/PatternPropertyValidationTests.cs index 7b5c968cb..fb582c169 100644 --- a/src/NJsonSchema.Tests/Validation/PatternPropertyValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/PatternPropertyValidationTests.cs @@ -11,10 +11,10 @@ public class PatternPropertyValidationTests public void When_there_are_no_properties_matching_pattern_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; schema.AllowAdditionalProperties = false; - schema.PatternProperties.Add("^[a-z]+$", new JsonProperty() { Type = JsonObjectType.Object}); + schema.PatternProperties.Add("^[a-z]+$", new JsonSchemaProperty() { Type = JsonObjectType.Object}); var token = new JObject(); token.Add("123", new JObject()); @@ -35,10 +35,10 @@ public void When_there_are_no_properties_matching_pattern_then_validation_fails( public void When_there_are_properties_matching_pattern_but_types_doesnt_match_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; schema.AllowAdditionalProperties = false; - schema.PatternProperties.Add("^[a-z]+$", new JsonProperty() { Type = JsonObjectType.Object}); + schema.PatternProperties.Add("^[a-z]+$", new JsonSchemaProperty() { Type = JsonObjectType.Object}); var token = new JObject(); token.Add("qwerty", new JArray()); @@ -56,10 +56,10 @@ public void When_there_are_properties_matching_pattern_but_types_doesnt_match_th public void When_there_are_properties_matching_pattern_and_types_matches_then_validation_succeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Object; schema.AllowAdditionalProperties = false; - schema.PatternProperties.Add("^[a-z]+$", new JsonProperty() { Type = JsonObjectType.Object}); + schema.PatternProperties.Add("^[a-z]+$", new JsonSchemaProperty() { Type = JsonObjectType.Object}); var token = new JObject(); token.Add("qwerty", new JObject()); diff --git a/src/NJsonSchema.Tests/Validation/SchemaTests.cs b/src/NJsonSchema.Tests/Validation/SchemaTests.cs index cc2b3227d..1bdfedcfa 100644 --- a/src/NJsonSchema.Tests/Validation/SchemaTests.cs +++ b/src/NJsonSchema.Tests/Validation/SchemaTests.cs @@ -316,7 +316,7 @@ public async Task When_no_additional_properties_are_allowed_then_this_error_is_r } "; - var schema = await JsonSchema4.FromJsonAsync(schemaData); + var schema = await JsonSchema.FromJsonAsync(schemaData); //// Act var errors = schema.Validate(@"{""Key"": ""Value""}"); @@ -372,7 +372,7 @@ public async Task When_multiple_types_fail_with_errors_take_the_best_group() }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var errors = schema.Validate(json); //// Assert @@ -405,7 +405,7 @@ public async Task When_datetime_with_regex_validation_then_datetime_is_not_alter }"; //// Act - var schema = await JsonSchema4.FromJsonAsync(schemaJson); + var schema = await JsonSchema.FromJsonAsync(schemaJson); var errors = schema.Validate(json); //// Assert diff --git a/src/NJsonSchema.Tests/Validation/UniqueItemsTests.cs b/src/NJsonSchema.Tests/Validation/UniqueItemsTests.cs index 0c62ee1dd..91ac5fc91 100644 --- a/src/NJsonSchema.Tests/Validation/UniqueItemsTests.cs +++ b/src/NJsonSchema.Tests/Validation/UniqueItemsTests.cs @@ -43,7 +43,7 @@ public async Task When_unique_items_is_set_and_items_are_objects_then_validation }]"; //// Act - var schema = await JsonSchema4.FromJsonAsync(jsonSchema); + var schema = await JsonSchema.FromJsonAsync(jsonSchema); var errors = schema.Validate(jsonData).ToList(); //// Assert diff --git a/src/NJsonSchema.Tests/Validation/ValueTypeValidationTests.cs b/src/NJsonSchema.Tests/Validation/ValueTypeValidationTests.cs index 1471cf75e..5ec285797 100644 --- a/src/NJsonSchema.Tests/Validation/ValueTypeValidationTests.cs +++ b/src/NJsonSchema.Tests/Validation/ValueTypeValidationTests.cs @@ -11,7 +11,7 @@ public class ValueTypeValidationTests public void When_string_required_and_string_provided_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; var token = new JValue("test"); @@ -27,7 +27,7 @@ public void When_string_required_and_string_provided_then_validation_succeeds() public void When_string_required_but_integer_provided_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; var token = new JValue(10); @@ -44,7 +44,7 @@ public void When_string_required_but_integer_provided_then_validation_fails() public void When_number_required_and_integer_provided_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Number; var token = new JValue(10); @@ -60,7 +60,7 @@ public void When_number_required_and_integer_provided_then_validation_succeeds() public void When_number_required_but_string_provided_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Number; var token = new JValue("foo"); @@ -77,7 +77,7 @@ public void When_number_required_but_string_provided_then_validation_fails() public void When_integer_required_and_integer_provided_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Integer; var token = new JValue(10); @@ -93,7 +93,7 @@ public void When_integer_required_and_integer_provided_then_validation_succeeds( public void When_integer_required_but_string_provided_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Integer; var token = new JValue("foo"); @@ -110,7 +110,7 @@ public void When_integer_required_but_string_provided_then_validation_fails() public void When_boolean_required_and_boolean_provided_then_validation_succeeds() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Boolean; var token = new JValue(true); @@ -126,7 +126,7 @@ public void When_boolean_required_and_boolean_provided_then_validation_succeeds( public void When_boolean_required_but_string_provided_then_validation_fails() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Boolean; var token = new JValue("foo"); @@ -143,7 +143,7 @@ public void When_boolean_required_but_string_provided_then_validation_fails() public void When_string_pattern_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Pattern = "aa(.*)aa"; @@ -161,7 +161,7 @@ public void When_string_pattern_does_not_match_then_it_should_fail() public void When_string_min_length_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.MinLength = 2; @@ -179,7 +179,7 @@ public void When_string_min_length_does_not_match_then_it_should_fail() public void When_string_max_length_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.MaxLength = 2; @@ -197,7 +197,7 @@ public void When_string_max_length_does_not_match_then_it_should_fail() public void When_integer_minimum_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Integer; schema.Minimum = 2; @@ -215,7 +215,7 @@ public void When_integer_minimum_does_not_match_then_it_should_fail() public void When_integer_maximum_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Integer; schema.Maximum = 2; @@ -233,7 +233,7 @@ public void When_integer_maximum_does_not_match_then_it_should_fail() public void When_number_minimum_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Number; schema.Minimum = 1.5m; @@ -251,7 +251,7 @@ public void When_number_minimum_does_not_match_then_it_should_fail() public void When_number_maximum_does_not_match_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.Number; schema.Maximum = 1.5m; @@ -269,7 +269,7 @@ public void When_number_maximum_does_not_match_then_it_should_fail() public void When_value_not_in_enumeration_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Enumeration.Add("Red"); schema.Enumeration.Add("Green"); @@ -289,7 +289,7 @@ public void When_value_not_in_enumeration_then_it_should_fail() public void When_value_in_enumeration_then_it_should_succeed() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Enumeration.Add("Red"); schema.Enumeration.Add("Green"); @@ -308,7 +308,7 @@ public void When_value_in_enumeration_then_it_should_succeed() public void When_value_is_wrong_type_in_enumeration_then_it_should_fail() { //// Arrange - var schema = new JsonSchema4(); + var schema = new JsonSchema(); schema.Type = JsonObjectType.String; schema.Enumeration.Add("1"); schema.Enumeration.Add("2"); diff --git a/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs b/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs index 692d5e073..48343e95e 100644 --- a/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs +++ b/src/NJsonSchema.Yaml/JsonAndYamlReferenceResolver.cs @@ -26,9 +26,9 @@ public JsonAndYamlReferenceResolver(JsonSchemaAppender schemaAppender) /// Creates the factory to be used in the FromJsonAsync method. /// The type name generator. /// The factory. - public static Func CreateJsonAndYamlReferenceResolverFactory(ITypeNameGenerator typeNameGenerator) + public static Func CreateJsonAndYamlReferenceResolverFactory(ITypeNameGenerator typeNameGenerator) { - JsonReferenceResolver ReferenceResolverFactory(JsonSchema4 schema) => + JsonReferenceResolver ReferenceResolverFactory(JsonSchema schema) => new JsonAndYamlReferenceResolver(new JsonSchemaAppender(schema, typeNameGenerator)); return ReferenceResolverFactory; diff --git a/src/NJsonSchema.Yaml/JsonSchemaYaml.cs b/src/NJsonSchema.Yaml/JsonSchemaYaml.cs index 33a87f7da..177eb6b52 100644 --- a/src/NJsonSchema.Yaml/JsonSchemaYaml.cs +++ b/src/NJsonSchema.Yaml/JsonSchemaYaml.cs @@ -18,34 +18,34 @@ namespace NJsonSchema.Yaml { - /// Extension methods to load and save from/to YAML. + /// Extension methods to load and save from/to YAML. public static class JsonSchemaYaml { - /// Deserializes a JSON string to a . + /// Deserializes a JSON string to a . /// The JSON string. /// The JSON Schema. - public static async Task FromYamlAsync(string data) + public static async Task FromYamlAsync(string data) { var factory = JsonAndYamlReferenceResolver.CreateJsonAndYamlReferenceResolverFactory(new DefaultTypeNameGenerator()); return await JsonSchemaYaml.FromYamlAsync(data, null, factory).ConfigureAwait(false); } - /// Deserializes a JSON string to a . + /// Deserializes a JSON string to a . /// The JSON string. /// The document path (URL or file path) for resolving relative document references. /// The JSON Schema. - public static async Task FromYamlAsync(string data, string documentPath) + public static async Task FromYamlAsync(string data, string documentPath) { var factory = JsonAndYamlReferenceResolver.CreateJsonAndYamlReferenceResolverFactory(new DefaultTypeNameGenerator()); return await FromYamlAsync(data, documentPath, factory).ConfigureAwait(false); } - /// Deserializes a JSON string to a . + /// Deserializes a JSON string to a . /// The JSON string. /// The document path (URL or file path) for resolving relative document references. /// The JSON reference resolver factory. /// The JSON Schema. - public static async Task FromYamlAsync(string data, string documentPath, Func referenceResolverFactory) + public static async Task FromYamlAsync(string data, string documentPath, Func referenceResolverFactory) { var deserializer = new DeserializerBuilder().Build(); var yamlObject = deserializer.Deserialize(new StringReader(data)); @@ -54,12 +54,12 @@ public static async Task FromYamlAsync(string data, string document .Build(); var json = serializer.Serialize(yamlObject); - return await JsonSchema4.FromJsonAsync(json, documentPath, referenceResolverFactory).ConfigureAwait(false); + return await JsonSchema.FromJsonAsync(json, documentPath, referenceResolverFactory).ConfigureAwait(false); } /// Converts the JSON Schema to YAML. /// The YAML string. - public static string ToYaml(this JsonSchema4 document) + public static string ToYaml(this JsonSchema document) { var json = document.ToJson(); var expConverter = new ExpandoObjectConverter(); @@ -71,8 +71,8 @@ public static string ToYaml(this JsonSchema4 document) /// Creates a JSON Schema from a JSON file. /// The file path. - /// The . - public static async Task FromFileAsync(string filePath) + /// The . + public static async Task FromFileAsync(string filePath) { var factory = JsonAndYamlReferenceResolver.CreateJsonAndYamlReferenceResolverFactory(new DefaultTypeNameGenerator()); return await FromFileAsync(filePath, factory).ConfigureAwait(false); @@ -81,8 +81,8 @@ public static async Task FromFileAsync(string filePath) /// Creates a JSON Schema from a JSON file. /// The file path. /// The JSON reference resolver factory. - /// The . - public static async Task FromFileAsync(string filePath, Func referenceResolverFactory) + /// The . + public static async Task FromFileAsync(string filePath, Func referenceResolverFactory) { var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false); return await FromYamlAsync(data, filePath, referenceResolverFactory).ConfigureAwait(false); @@ -91,8 +91,8 @@ public static async Task FromFileAsync(string filePath, FuncCreates a JSON Schema from an URL. /// The URL. /// The JSON reference resolver factory. - /// The . - public static async Task FromUrlAsync(string url, Func referenceResolverFactory) + /// The . + public static async Task FromUrlAsync(string url, Func referenceResolverFactory) { var data = await DynamicApis.HttpGetAsync(url).ConfigureAwait(false); return await FromYamlAsync(data, url, referenceResolverFactory).ConfigureAwait(false); diff --git a/src/NJsonSchema.sln b/src/NJsonSchema.sln index 67804ddc6..8cb738830 100644 --- a/src/NJsonSchema.sln +++ b/src/NJsonSchema.sln @@ -31,6 +31,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NJsonSchema.Benchmark", "NJ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NJsonSchema.Yaml.Tests", "NJsonSchema.Yaml.Tests\NJsonSchema.Yaml.Tests.csproj", "{990EF464-C967-4E08-8C3D-0568A47B6D2A}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{863B2D88-A0BD-4466-8583-AAD0B8D3F182}" + ProjectSection(SolutionItems) = preProject + ..\README.md = ..\README.md + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/src/NJsonSchema/DefaultTypeNameGenerator.cs b/src/NJsonSchema/DefaultTypeNameGenerator.cs index 09a846e87..a393190e8 100644 --- a/src/NJsonSchema/DefaultTypeNameGenerator.cs +++ b/src/NJsonSchema/DefaultTypeNameGenerator.cs @@ -27,7 +27,7 @@ public class DefaultTypeNameGenerator : ITypeNameGenerator /// The type name hint. /// The reserved type names. /// The type name. - public virtual string Generate(JsonSchema4 schema, string typeNameHint, IEnumerable reservedTypeNames) + public virtual string Generate(JsonSchema schema, string typeNameHint, IEnumerable reservedTypeNames) { if (string.IsNullOrEmpty(typeNameHint) && !string.IsNullOrEmpty(schema.DocumentPath)) typeNameHint = schema.DocumentPath.Replace("\\", "/").Split('/').Last(); @@ -54,7 +54,7 @@ public virtual string Generate(JsonSchema4 schema, string typeNameHint, IEnumera /// The schema. /// The type name hint. /// The type name. - protected virtual string Generate(JsonSchema4 schema, string typeNameHint) + protected virtual string Generate(JsonSchema schema, string typeNameHint) { if (string.IsNullOrEmpty(typeNameHint) && schema.HasTypeNameTitle) { diff --git a/src/NJsonSchema/DefaultSchemaNameGenerator.cs b/src/NJsonSchema/Generation/DefaultSchemaNameGenerator.cs similarity index 76% rename from src/NJsonSchema/DefaultSchemaNameGenerator.cs rename to src/NJsonSchema/Generation/DefaultSchemaNameGenerator.cs index 990559f15..367a55233 100644 --- a/src/NJsonSchema/DefaultSchemaNameGenerator.cs +++ b/src/NJsonSchema/Generation/DefaultSchemaNameGenerator.cs @@ -7,10 +7,12 @@ //----------------------------------------------------------------------- using System; +using System.Text.RegularExpressions; using Namotion.Reflection; +using Newtonsoft.Json; using NJsonSchema.Annotations; -namespace NJsonSchema +namespace NJsonSchema.Generation { /// The default schema name generator implementation. public class DefaultSchemaNameGenerator : ISchemaNameGenerator @@ -20,13 +22,19 @@ public class DefaultSchemaNameGenerator : ISchemaNameGenerator /// The new name. public virtual string Generate(Type type) { - var jsonSchemaAttribute = type.ToCachedType().GetTypeAttribute(); + var cachedType = type.ToCachedType(); + + var jsonSchemaAttribute = cachedType.GetTypeAttribute(); if (!string.IsNullOrEmpty(jsonSchemaAttribute?.Name)) + { return jsonSchemaAttribute.Name; + } - //var jsonObjectAttribute = type.GetTypeInfo().GetCustomAttribute(); + //var jsonObjectAttribute = cachedType.GetTypeAttribute(); //if (!string.IsNullOrEmpty(jsonObjectAttribute.Title) && Regex.IsMatch(jsonObjectAttribute.Title, "^[a-zA-Z0-9_]*$")) + //{ // return jsonObjectAttribute.Title; + //} return type.GetDisplayName(); } diff --git a/src/NJsonSchema/EnumHandling.cs b/src/NJsonSchema/Generation/EnumHandling.cs similarity index 95% rename from src/NJsonSchema/EnumHandling.cs rename to src/NJsonSchema/Generation/EnumHandling.cs index bea0acdc0..181818ab2 100644 --- a/src/NJsonSchema/EnumHandling.cs +++ b/src/NJsonSchema/Generation/EnumHandling.cs @@ -1,23 +1,23 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) Rico Suter. All rights reserved. -// -// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md -// Rico Suter, mail@rsuter.com -//----------------------------------------------------------------------- - -namespace NJsonSchema -{ - /// Defines the enum handling. - public enum EnumHandling - { - /// Generates an integer field without enumeration (except when using StringEnumConverter). - Integer, - - /// Generates a string field with JSON Schema enumeration. - String, - - /// Generates a camel-cased string field with JSON Schema enumeration. - CamelCaseString, - } +//----------------------------------------------------------------------- +// +// Copyright (c) Rico Suter. All rights reserved. +// +// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md +// Rico Suter, mail@rsuter.com +//----------------------------------------------------------------------- + +namespace NJsonSchema.Generation +{ + /// Defines the enum handling. + public enum EnumHandling + { + /// Generates an integer field without enumeration (except when using StringEnumConverter). + Integer, + + /// Generates a string field with JSON Schema enumeration. + String, + + /// Generates a camel-cased string field with JSON Schema enumeration. + CamelCaseString, + } } \ No newline at end of file diff --git a/src/NJsonSchema/ISchemaNameGenerator.cs b/src/NJsonSchema/Generation/ISchemaNameGenerator.cs similarity index 95% rename from src/NJsonSchema/ISchemaNameGenerator.cs rename to src/NJsonSchema/Generation/ISchemaNameGenerator.cs index 774d6918a..e196c114f 100644 --- a/src/NJsonSchema/ISchemaNameGenerator.cs +++ b/src/NJsonSchema/Generation/ISchemaNameGenerator.cs @@ -8,7 +8,7 @@ using System; -namespace NJsonSchema +namespace NJsonSchema.Generation { /// The schema name generator. public interface ISchemaNameGenerator diff --git a/src/NJsonSchema/Generation/JsonSchemaGenerator.cs b/src/NJsonSchema/Generation/JsonSchemaGenerator.cs index 837fa40b2..4fc8ed5c5 100644 --- a/src/NJsonSchema/Generation/JsonSchemaGenerator.cs +++ b/src/NJsonSchema/Generation/JsonSchemaGenerator.cs @@ -24,7 +24,7 @@ namespace NJsonSchema.Generation { - /// Generates a object for a given type. + /// Generates a object for a given type. public class JsonSchemaGenerator { private static readonly Dictionary DataTypeFormats = new Dictionary @@ -47,63 +47,63 @@ public JsonSchemaGenerator(JsonSchemaGeneratorSettings settings) /// Gets the settings. public JsonSchemaGeneratorSettings Settings { get; } - /// Generates a object for the given type and adds the mapping to the given resolver. + /// Generates a object for the given type and adds the mapping to the given resolver. /// The type. /// The schema. /// Could not find value type of dictionary type. - public async Task GenerateAsync(Type type) + public async Task GenerateAsync(Type type) { - var schema = new JsonSchema4(); + var schema = new JsonSchema(); var schemaResolver = new JsonSchemaResolver(schema, Settings); await GenerateAsync(type.ToContextualType(), schema, schemaResolver).ConfigureAwait(false); return schema; } - /// Generates a object for the given type and adds the mapping to the given resolver. + /// Generates a object for the given type and adds the mapping to the given resolver. /// The type. /// The schema resolver. /// The schema. /// Could not find value type of dictionary type. - public Task GenerateAsync(Type type, JsonSchemaResolver schemaResolver) + public Task GenerateAsync(Type type, JsonSchemaResolver schemaResolver) { - return GenerateAsync(type, schemaResolver); + return GenerateAsync(type, schemaResolver); } - /// Generates a object for the given type and adds the mapping to the given resolver. + /// Generates a object for the given type and adds the mapping to the given resolver. /// The type. /// The schema resolver. /// The schema. /// Could not find value type of dictionary type. public Task GenerateAsync(Type type, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { return GenerateAsync(type.ToContextualType(), schemaResolver); } - /// Generates a object for the given type and adds the mapping to the given resolver. + /// Generates a object for the given type and adds the mapping to the given resolver. /// The type. /// The schema resolver. /// The schema. /// Could not find value type of dictionary type. - public async Task GenerateAsync(ContextualType contextualType, JsonSchemaResolver schemaResolver) + public async Task GenerateAsync(ContextualType contextualType, JsonSchemaResolver schemaResolver) { - return await GenerateAsync(contextualType, schemaResolver).ConfigureAwait(false); + return await GenerateAsync(contextualType, schemaResolver).ConfigureAwait(false); } - /// Generates a object for the given type and adds the mapping to the given resolver. + /// Generates a object for the given type and adds the mapping to the given resolver. /// The type. /// The schema resolver. /// The schema. /// Could not find value type of dictionary type. public async Task GenerateAsync(ContextualType contextualType, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { var schema = new TSchemaType(); await GenerateAsync(contextualType, schema, schemaResolver).ConfigureAwait(false); return schema; } - /// Generates a object for the given type and adds the mapping to the given resolver. + /// Generates a object for the given type and adds the mapping to the given resolver. /// The type of the schema. /// The type. /// The schema. @@ -111,7 +111,7 @@ public async Task GenerateAsync(ContextualType context /// The schema. /// Could not find value type of dictionary type. public virtual async Task GenerateAsync(ContextualType contextualType, TSchemaType schema, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { var type = contextualType.OriginalType; @@ -148,7 +148,7 @@ public virtual async Task GenerateAsync(ContextualType contextualTy { schema.Reference = schemaResolver.GetSchema(type, false); } - else if (schema.GetType() == typeof(JsonSchema4)) + else if (schema.GetType() == typeof(JsonSchema)) { await GenerateObjectAsync(type, typeDescription, schema, schemaResolver).ConfigureAwait(false); } @@ -184,8 +184,8 @@ public virtual async Task GenerateAsync(ContextualType contextualTy public async Task GenerateWithReferenceAsync( ContextualType contextualType, JsonSchemaResolver schemaResolver, - Func transformation = null) - where TSchemaType : JsonSchema4, new() + Func transformation = null) + where TSchemaType : JsonSchema, new() { return await GenerateWithReferenceAndNullabilityAsync(contextualType, false, schemaResolver, transformation).ConfigureAwait(false); } @@ -199,8 +199,8 @@ public async Task GenerateWithReferenceAsync( /// The requested schema object. public async Task GenerateWithReferenceAndNullabilityAsync( ContextualType contextualType, JsonSchemaResolver schemaResolver, - Func transformation = null) - where TSchemaType : JsonSchema4, new() + Func transformation = null) + where TSchemaType : JsonSchema, new() { var typeDescription = Settings.ReflectionService.GetDescription(contextualType, Settings); return await GenerateWithReferenceAndNullabilityAsync(contextualType, typeDescription.IsNullable, schemaResolver, transformation).ConfigureAwait(false); @@ -215,13 +215,13 @@ public async Task GenerateWithReferenceAndNullabilityAsyncThe requested schema object. public virtual async Task GenerateWithReferenceAndNullabilityAsync( ContextualType contextualType, bool isNullable, JsonSchemaResolver schemaResolver, - Func transformation = null) - where TSchemaType : JsonSchema4, new() + Func transformation = null) + where TSchemaType : JsonSchema, new() { var typeDescription = Settings.ReflectionService.GetDescription(contextualType, Settings); var requiresSchemaReference = typeDescription.RequiresSchemaReference(Settings.TypeMappers); - JsonSchema4 referencedSchema; + JsonSchema referencedSchema; if (!requiresSchemaReference) { var schema = await GenerateAsync(contextualType, schemaResolver).ConfigureAwait(false); @@ -238,8 +238,8 @@ public virtual async Task GenerateWithReferenceAndNullabilityAsync< { if (schema.Type == JsonObjectType.None) { - schema.OneOf.Add(new JsonSchema4 { Type = JsonObjectType.None }); - schema.OneOf.Add(new JsonSchema4 { Type = JsonObjectType.Null }); + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.None }); + schema.OneOf.Add(new JsonSchema { Type = JsonObjectType.Null }); } else { @@ -261,7 +261,7 @@ public virtual async Task GenerateWithReferenceAndNullabilityAsync< } else { - referencedSchema = await GenerateAsync(contextualType, schemaResolver).ConfigureAwait(false); + referencedSchema = await GenerateAsync(contextualType, schemaResolver).ConfigureAwait(false); } var referencingSchema = new TSchemaType(); @@ -274,7 +274,7 @@ public virtual async Task GenerateWithReferenceAndNullabilityAsync< { if (Settings.SchemaType == SchemaType.JsonSchema) { - referencingSchema.OneOf.Add(new JsonSchema4 { Type = JsonObjectType.Null }); + referencingSchema.OneOf.Add(new JsonSchema { Type = JsonObjectType.Null }); } else if (Settings.SchemaType == SchemaType.OpenApi3 || Settings.GenerateCustomNullableProperties) { @@ -292,14 +292,14 @@ public virtual async Task GenerateWithReferenceAndNullabilityAsync< } else if (Settings.SchemaType != SchemaType.Swagger2) { - referencingSchema.OneOf.Add(new JsonSchema4 + referencingSchema.OneOf.Add(new JsonSchema { Reference = referencedSchema.ActualSchema }); } else { - referencingSchema.AllOf.Add(new JsonSchema4 + referencingSchema.AllOf.Add(new JsonSchema { Reference = referencedSchema.ActualSchema }); @@ -312,7 +312,7 @@ public virtual async Task GenerateWithReferenceAndNullabilityAsync< /// The property. /// The member info. /// The property name. - public virtual string GetPropertyName(Newtonsoft.Json.Serialization.JsonProperty jsonProperty, MemberInfo memberInfo) + public virtual string GetPropertyName(JsonProperty jsonProperty, MemberInfo memberInfo) { try { @@ -340,7 +340,7 @@ public virtual string GetPropertyName(Newtonsoft.Json.Serialization.JsonProperty /// The schema resolver. /// The task. protected virtual async Task GenerateObjectAsync(Type type, - JsonTypeDescription typeDescription, JsonSchema4 schema, JsonSchemaResolver schemaResolver) + JsonTypeDescription typeDescription, JsonSchema schema, JsonSchemaResolver schemaResolver) { schemaResolver.AddSchema(type, false, schema); @@ -378,7 +378,7 @@ protected virtual async Task GenerateObjectAsync(Type type, } private async Task ApplyAdditionalPropertiesAsync(Type type, TSchemaType schema, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { var extensionDataProperty = type.GetContextualRuntimeProperties() .FirstOrDefault(p => p.GetContextAttribute() != null); @@ -388,7 +388,7 @@ private async Task ApplyAdditionalPropertiesAsync(Type type, TSchem var genericTypeArguments = extensionDataProperty.GenericArguments; var extensionDataPropertyType = genericTypeArguments.Length == 2 ? genericTypeArguments[1] : typeof(object).ToContextualType(); - schema.AdditionalPropertiesSchema = await GenerateWithReferenceAndNullabilityAsync( + schema.AdditionalPropertiesSchema = await GenerateWithReferenceAndNullabilityAsync( extensionDataPropertyType, schemaResolver).ConfigureAwait(false); } else @@ -397,7 +397,7 @@ private async Task ApplyAdditionalPropertiesAsync(Type type, TSchem } } - private async Task ApplySchemaProcessorsAsync(ContextualType contextualType, JsonSchema4 schema, JsonSchemaResolver schemaResolver) + private async Task ApplySchemaProcessorsAsync(ContextualType contextualType, JsonSchema schema, JsonSchemaResolver schemaResolver) { var context = new SchemaProcessorContext(contextualType.OriginalType, schema, schemaResolver, this, Settings); foreach (var processor in Settings.SchemaProcessors) @@ -417,7 +417,7 @@ private async Task ApplySchemaProcessorsAsync(ContextualType contextualType, Jso } private void ApplyExtensionDataAttributes(ContextualType contextualType, TSchemaType schema) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { // class var extensionDataAttributes = contextualType.GetAttributes().ToArray(); @@ -437,7 +437,7 @@ private void ApplyExtensionDataAttributes(ContextualType contextual } private async Task TryHandleSpecialTypesAsync(ContextualType contextualType, TSchemaType schema, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { var typeMapper = Settings.TypeMappers.FirstOrDefault(m => m.MappedType == contextualType.OriginalType); if (typeMapper == null && contextualType.OriginalType.GetTypeInfo().IsGenericType) @@ -465,7 +465,7 @@ private async Task TryHandleSpecialTypesAsync(ContextualType private async Task GenerateArray( TSchemaType schema, ContextualType contextualType, JsonTypeDescription typeDescription, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { #pragma warning disable 1998 @@ -479,7 +479,7 @@ private async Task GenerateArray( var itemIsNullable = contextualType.GetContextAttribute() != null || contextualItemType.Nullability == Nullability.Nullable; - schema.Item = await GenerateWithReferenceAndNullabilityAsync( + schema.Item = await GenerateWithReferenceAndNullabilityAsync( contextualItemType, itemIsNullable, schemaResolver, async (itemSchema, typeSchema) => { if (Settings.GenerateXmlObjects) @@ -495,7 +495,7 @@ private async Task GenerateArray( } else { - schema.Item = JsonSchema4.CreateAnySchema(); + schema.Item = JsonSchema.CreateAnySchema(); } #pragma warning restore 1998 @@ -503,7 +503,7 @@ private async Task GenerateArray( private async Task GenerateEnum( TSchemaType schema, ContextualType contextualType, JsonTypeDescription typeDescription, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { var type = contextualType.Type; @@ -512,7 +512,7 @@ private async Task GenerateEnum( { schema.Reference = schemaResolver.GetSchema(type, isIntegerEnumeration); } - else if (schema.GetType() == typeof(JsonSchema4)) + else if (schema.GetType() == typeof(JsonSchema)) { typeDescription.ApplyType(schema); schema.Description = await type.GetXmlSummaryAsync().ConfigureAwait(false); @@ -529,28 +529,28 @@ private async Task GenerateEnum( /// Could not find value type of dictionary type. private async Task GenerateDictionaryAsync(TSchemaType schema, ContextualType contextualType, JsonSchemaResolver schemaResolver) - where TSchemaType : JsonSchema4, new() + where TSchemaType : JsonSchema, new() { var genericTypeArguments = contextualType.GenericArguments; var keyType = genericTypeArguments.Length == 2 ? genericTypeArguments[0] : typeof(string).ToContextualType(); if (keyType.OriginalType.GetTypeInfo().IsEnum) { - schema.DictionaryKey = await GenerateWithReferenceAsync( + schema.DictionaryKey = await GenerateWithReferenceAsync( keyType, schemaResolver).ConfigureAwait(false); } var valueType = genericTypeArguments.Length == 2 ? genericTypeArguments[1] : typeof(object).ToContextualType(); if (valueType.OriginalType == typeof(object)) { - schema.AdditionalPropertiesSchema = JsonSchema4.CreateAnySchema(); + schema.AdditionalPropertiesSchema = JsonSchema.CreateAnySchema(); } else { var valueIsNullable = valueType.GetContextAttribute() != null || valueType.OriginalType.Name == "Nullable`1"; - schema.AdditionalPropertiesSchema = await GenerateWithReferenceAndNullabilityAsync( + schema.AdditionalPropertiesSchema = await GenerateWithReferenceAndNullabilityAsync( valueType, valueIsNullable, schemaResolver/*, async (s, r) => { // TODO: Generate xml for key @@ -564,7 +564,7 @@ private async Task GenerateDictionaryAsync(TSchemaType schema, Cont schema.AllowAdditionalProperties = true; } - private async Task GeneratePropertiesAsync(Type type, JsonSchema4 schema, JsonSchemaResolver schemaResolver) + private async Task GeneratePropertiesAsync(Type type, JsonSchema schema, JsonSchemaResolver schemaResolver) { #if !LEGACY var members = type.GetTypeInfo() @@ -636,7 +636,7 @@ private async Task GeneratePropertiesAsync(Type type, JsonSchema4 schema, JsonSc var memberType = (memberInfo as ContextualPropertyInfo)?.PropertyInfo.PropertyType ?? (memberInfo as ContextualFieldInfo)?.FieldInfo.FieldType; - var property = new Newtonsoft.Json.Serialization.JsonProperty + var jsonProperty = new JsonProperty { AttributeProvider = new ReflectionAttributeProvider(memberInfo), PropertyType = memberType, @@ -645,19 +645,19 @@ private async Task GeneratePropertiesAsync(Type type, JsonSchema4 schema, JsonSc if (attribute != null) { - property.PropertyName = attribute.PropertyName ?? memberInfo.Name; - property.Required = attribute.Required; - property.DefaultValueHandling = attribute.DefaultValueHandling; - property.TypeNameHandling = attribute.TypeNameHandling; - property.NullValueHandling = attribute.NullValueHandling; - property.TypeNameHandling = attribute.TypeNameHandling; + jsonProperty.PropertyName = attribute.PropertyName ?? memberInfo.Name; + jsonProperty.Required = attribute.Required; + jsonProperty.DefaultValueHandling = attribute.DefaultValueHandling; + jsonProperty.TypeNameHandling = attribute.TypeNameHandling; + jsonProperty.NullValueHandling = attribute.NullValueHandling; + jsonProperty.TypeNameHandling = attribute.TypeNameHandling; } else { - property.PropertyName = memberInfo.Name; + jsonProperty.PropertyName = memberInfo.Name; } - await LoadPropertyOrFieldAsync(property, memberInfo, type, schema, schemaResolver).ConfigureAwait(false); + await LoadPropertyOrFieldAsync(jsonProperty, memberInfo, type, schema, schemaResolver).ConfigureAwait(false); } } } @@ -733,7 +733,7 @@ private async Task AddKnownTypeAsync(Type type, JsonSchemaResolver schemaResolve } } - private async Task GenerateInheritanceAsync(Type type, JsonSchema4 schema, JsonSchemaResolver schemaResolver) + private async Task GenerateInheritanceAsync(Type type, JsonSchema schema, JsonSchemaResolver schemaResolver) { var baseType = type.GetTypeInfo().BaseType; if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType)) @@ -755,7 +755,7 @@ private async Task GenerateInheritanceAsync(Type type, JsonSchema4 } else { - var actualSchema = new JsonSchema4(); + var actualSchema = new JsonSchema(); await GeneratePropertiesAsync(type, actualSchema, schemaResolver).ConfigureAwait(false); await ApplyAdditionalPropertiesAsync(type, actualSchema, schemaResolver).ConfigureAwait(false); @@ -776,7 +776,7 @@ private async Task GenerateInheritanceAsync(Type type, JsonSchema4 schemaResolver.AppendSchema(baseSchema.ActualSchema, Settings.SchemaNameGenerator.Generate(baseType)); } - schema.AllOf.Add(new JsonSchema4 + schema.AllOf.Add(new JsonSchema { Reference = baseSchema.ActualSchema }); @@ -823,7 +823,7 @@ private async Task GenerateInheritanceAsync(Type type, JsonSchema4 return null; } - private void GenerateInheritanceDiscriminator(Type type, JsonSchema4 schema, JsonSchema4 typeSchema) + private void GenerateInheritanceDiscriminator(Type type, JsonSchema schema, JsonSchema typeSchema) { if (!Settings.GetActualFlattenInheritanceHierarchy(type)) { @@ -833,7 +833,7 @@ private void GenerateInheritanceDiscriminator(Type type, JsonSchema4 schema, Jso var discriminatorName = TryGetInheritanceDiscriminatorName(discriminatorConverter); // Existing property can be discriminator only if it has String type - if (typeSchema.Properties.TryGetValue(discriminatorName, out JsonProperty existingProperty) && + if (typeSchema.Properties.TryGetValue(discriminatorName, out JsonSchemaProperty existingProperty) && (existingProperty.Type & JsonObjectType.String) == 0) { throw new InvalidOperationException("The JSON discriminator property '" + discriminatorName + "' must be a string property on type '" + type.FullName + "' (it is recommended to not implement the discriminator property at all)."); @@ -846,7 +846,7 @@ private void GenerateInheritanceDiscriminator(Type type, JsonSchema4 schema, Jso }; typeSchema.DiscriminatorObject = discriminator; - typeSchema.Properties[discriminatorName] = new JsonProperty + typeSchema.Properties[discriminatorName] = new JsonSchemaProperty { Type = JsonObjectType.String, IsRequired = true @@ -889,7 +889,7 @@ private string TryGetInheritanceDiscriminatorName(dynamic jsonInheritanceConvert return JsonInheritanceConverter.DefaultDiscriminatorName; } - private void LoadEnumerations(Type type, JsonSchema4 schema, JsonTypeDescription typeDescription) + private void LoadEnumerations(Type type, JsonSchema schema, JsonTypeDescription typeDescription) { schema.Type = typeDescription.Type; schema.Enumeration.Clear(); @@ -934,7 +934,7 @@ private void LoadEnumerations(Type type, JsonSchema4 schema, JsonTypeDescription } } - private async Task LoadPropertyOrFieldAsync(Newtonsoft.Json.Serialization.JsonProperty jsonProperty, ContextualMemberInfo memberInfo, Type parentType, JsonSchema4 parentSchema, JsonSchemaResolver schemaResolver) + private async Task LoadPropertyOrFieldAsync(JsonProperty jsonProperty, ContextualMemberInfo memberInfo, Type parentType, JsonSchema parentSchema, JsonSchemaResolver schemaResolver) { var propertyTypeDescription = Settings.ReflectionService.GetDescription(memberInfo, Settings); if (jsonProperty.Ignored == false && IsPropertyIgnoredBySettings(memberInfo) == false) @@ -959,7 +959,7 @@ private async Task LoadPropertyOrFieldAsync(Newtonsoft.Json.Serialization.JsonPr (bool)isDataContractMemberRequired == false && (jsonProperty.Required == Required.Default || jsonProperty.Required == Required.AllowNull); - Func TransformSchema = async (propertySchema, typeSchema) => + Func TransformSchema = async (propertySchema, typeSchema) => { if (Settings.GenerateXmlObjects) { @@ -1049,7 +1049,7 @@ private bool HasDataContractAttribute(Type parentType) /// The schema. /// The property type description. /// The attributes. - public virtual void ApplyDataAnnotations(JsonSchema4 schema, JsonTypeDescription typeDescription, IEnumerable parentAttributes) + public virtual void ApplyDataAnnotations(JsonSchema schema, JsonTypeDescription typeDescription, IEnumerable parentAttributes) { // TODO: Refactor out @@ -1145,7 +1145,7 @@ public virtual void ApplyDataAnnotations(JsonSchema4 schema, JsonTypeDescription } } - private void ApplyRangeAttribute(JsonSchema4 schema, IEnumerable parentAttributes) + private void ApplyRangeAttribute(JsonSchema schema, IEnumerable parentAttributes) { dynamic rangeAttribute = parentAttributes.TryGetAssignableToTypeName("System.ComponentModel.DataAnnotations.RangeAttribute"); if (rangeAttribute != null) @@ -1192,23 +1192,23 @@ private void ApplyRangeAttribute(JsonSchema4 schema, IEnumerable pare } } - private object ConvertDefaultValue(Newtonsoft.Json.Serialization.JsonProperty property) + private object ConvertDefaultValue(JsonProperty jsonProperty) { - if (property.DefaultValue != null && property.DefaultValue.GetType().GetTypeInfo().IsEnum) + if (jsonProperty.DefaultValue != null && jsonProperty.DefaultValue.GetType().GetTypeInfo().IsEnum) { - var hasStringEnumConverter = typeof(StringEnumConverter).GetTypeInfo().IsAssignableFrom(property.Converter?.GetType().GetTypeInfo()); + var hasStringEnumConverter = typeof(StringEnumConverter).GetTypeInfo().IsAssignableFrom(jsonProperty.Converter?.GetType().GetTypeInfo()); if (hasStringEnumConverter) { - return property.DefaultValue.ToString(); + return jsonProperty.DefaultValue.ToString(); } else { - return (int)property.DefaultValue; + return (int)jsonProperty.DefaultValue; } } else { - return property.DefaultValue; + return jsonProperty.DefaultValue; } } } diff --git a/src/NJsonSchema/JsonSchemaResolver.cs b/src/NJsonSchema/Generation/JsonSchemaResolver.cs similarity index 87% rename from src/NJsonSchema/JsonSchemaResolver.cs rename to src/NJsonSchema/Generation/JsonSchemaResolver.cs index c0684509a..928f119c4 100644 --- a/src/NJsonSchema/JsonSchemaResolver.cs +++ b/src/NJsonSchema/Generation/JsonSchemaResolver.cs @@ -1,72 +1,72 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) Rico Suter. All rights reserved. -// -// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md -// Rico Suter, mail@rsuter.com -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using NJsonSchema.Generation; - -namespace NJsonSchema -{ - /// Manager which resolves types to schemas and appends missing schemas to the root object. - public class JsonSchemaResolver : JsonSchemaAppender - { - private readonly Dictionary _mappings = new Dictionary(); - private readonly JsonSchemaGeneratorSettings _settings; - - /// Initializes a new instance of the class. - /// The root schema. - /// The settings. - public JsonSchemaResolver(object rootObject, JsonSchemaGeneratorSettings settings) - : base(rootObject, settings.TypeNameGenerator) - { - _settings = settings; - } - - /// Determines whether the specified type has a schema. - /// The type. - /// Specifies whether the type is an integer enum. - /// true when the mapping exists. - public bool HasSchema(Type type, bool isIntegerEnumeration) - { - return _mappings.ContainsKey(GetKey(type, isIntegerEnumeration)); - } - - /// Gets the schema for a given type. - /// The type. - /// Specifies whether the type is an integer enum. - /// The schema. - public JsonSchema4 GetSchema(Type type, bool isIntegerEnumeration) - { - return _mappings[GetKey(type, isIntegerEnumeration)]; - } - - /// Adds a schema to type mapping. - /// The type. - /// Specifies whether the type is an integer enum. - /// The schema. - /// Added schema is not a JsonSchema4 instance. - public virtual void AddSchema(Type type, bool isIntegerEnumeration, JsonSchema4 schema) - { - if (schema.GetType() != typeof(JsonSchema4)) - throw new InvalidOperationException("Added schema is not a JsonSchema4 instance."); - - if (schema != RootObject) - AppendSchema(schema, _settings.SchemaNameGenerator.Generate(type)); - - _mappings.Add(GetKey(type, isIntegerEnumeration), schema); - } - - /// Gets all the schemas. - public IEnumerable Schemas => _mappings.Values; - - private string GetKey(Type type, bool isIntegerEnum) - { - return type.FullName + (isIntegerEnum ? ":Integer" : string.Empty); - } - } +//----------------------------------------------------------------------- +// +// Copyright (c) Rico Suter. All rights reserved. +// +// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md +// Rico Suter, mail@rsuter.com +//----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using NJsonSchema.Generation; + +namespace NJsonSchema.Generation +{ + /// Manager which resolves types to schemas and appends missing schemas to the root object. + public class JsonSchemaResolver : JsonSchemaAppender + { + private readonly Dictionary _mappings = new Dictionary(); + private readonly JsonSchemaGeneratorSettings _settings; + + /// Initializes a new instance of the class. + /// The root schema. + /// The settings. + public JsonSchemaResolver(object rootObject, JsonSchemaGeneratorSettings settings) + : base(rootObject, settings.TypeNameGenerator) + { + _settings = settings; + } + + /// Determines whether the specified type has a schema. + /// The type. + /// Specifies whether the type is an integer enum. + /// true when the mapping exists. + public bool HasSchema(Type type, bool isIntegerEnumeration) + { + return _mappings.ContainsKey(GetKey(type, isIntegerEnumeration)); + } + + /// Gets the schema for a given type. + /// The type. + /// Specifies whether the type is an integer enum. + /// The schema. + public JsonSchema GetSchema(Type type, bool isIntegerEnumeration) + { + return _mappings[GetKey(type, isIntegerEnumeration)]; + } + + /// Adds a schema to type mapping. + /// The type. + /// Specifies whether the type is an integer enum. + /// The schema. + /// Added schema is not a JsonSchema4 instance. + public virtual void AddSchema(Type type, bool isIntegerEnumeration, JsonSchema schema) + { + if (schema.GetType() != typeof(JsonSchema)) + throw new InvalidOperationException("Added schema is not a JsonSchema4 instance."); + + if (schema != RootObject) + AppendSchema(schema, _settings.SchemaNameGenerator.Generate(type)); + + _mappings.Add(GetKey(type, isIntegerEnumeration), schema); + } + + /// Gets all the schemas. + public IEnumerable Schemas => _mappings.Values; + + private string GetKey(Type type, bool isIntegerEnum) + { + return type.FullName + (isIntegerEnum ? ":Integer" : string.Empty); + } + } } \ No newline at end of file diff --git a/src/NJsonSchema/Generation/JsonTypeDescription.cs b/src/NJsonSchema/Generation/JsonTypeDescription.cs index b9751aa7b..2aed0f7c1 100644 --- a/src/NJsonSchema/Generation/JsonTypeDescription.cs +++ b/src/NJsonSchema/Generation/JsonTypeDescription.cs @@ -101,7 +101,7 @@ public bool RequiresSchemaReference(IEnumerable typeMappers) /// Applies the type and format to the given schema. /// The JSON schema. - public void ApplyType(JsonSchema4 schema) + public void ApplyType(JsonSchema schema) { schema.Type = Type; schema.Format = Format; diff --git a/src/NJsonSchema/PropertyNameHandling.cs b/src/NJsonSchema/Generation/PropertyNameHandling.cs similarity index 97% rename from src/NJsonSchema/PropertyNameHandling.cs rename to src/NJsonSchema/Generation/PropertyNameHandling.cs index f320f214e..1cff21497 100644 --- a/src/NJsonSchema/PropertyNameHandling.cs +++ b/src/NJsonSchema/Generation/PropertyNameHandling.cs @@ -10,7 +10,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -namespace NJsonSchema +namespace NJsonSchema.Generation { /// Defines the property name handling. public enum PropertyNameHandling diff --git a/src/NJsonSchema/ReferenceTypeNullHandling.cs b/src/NJsonSchema/Generation/ReferenceTypeNullHandling.cs similarity index 96% rename from src/NJsonSchema/ReferenceTypeNullHandling.cs rename to src/NJsonSchema/Generation/ReferenceTypeNullHandling.cs index 50d39aa1d..716e5d77a 100644 --- a/src/NJsonSchema/ReferenceTypeNullHandling.cs +++ b/src/NJsonSchema/Generation/ReferenceTypeNullHandling.cs @@ -6,7 +6,7 @@ // Rico Suter, mail@rsuter.com //----------------------------------------------------------------------- -namespace NJsonSchema +namespace NJsonSchema.Generation { /// Specifies the default null handling for reference types when no nullability information is available. public enum ReferenceTypeNullHandling diff --git a/src/NJsonSchema/Generation/SampleJsonSchemaGenerator.cs b/src/NJsonSchema/Generation/SampleJsonSchemaGenerator.cs index bc315376b..c929e5812 100644 --- a/src/NJsonSchema/Generation/SampleJsonSchemaGenerator.cs +++ b/src/NJsonSchema/Generation/SampleJsonSchemaGenerator.cs @@ -21,23 +21,23 @@ public class SampleJsonSchemaGenerator /// Generates the JSON Schema for the given JSON data. /// The JSON data. /// The JSON Schema. - public JsonSchema4 Generate(string json) + public JsonSchema Generate(string json) { var token = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat }); - var schema = new JsonSchema4(); + var schema = new JsonSchema(); Generate(token, schema, schema, "Anonymous"); return schema; } - private void Generate(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema, string typeNameHint) + private void Generate(JToken token, JsonSchema schema, JsonSchema rootSchema, string typeNameHint) { if (schema != rootSchema && token.Type == JTokenType.Object) { - JsonSchema4 referencedSchema = null; + JsonSchema referencedSchema = null; if (token is JObject obj) { var properties = obj.Properties(); @@ -51,7 +51,7 @@ private void Generate(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema, if (referencedSchema == null) { - referencedSchema = new JsonSchema4(); + referencedSchema = new JsonSchema(); AddSchemaDefinition(rootSchema, referencedSchema, typeNameHint); } @@ -63,7 +63,7 @@ private void Generate(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema, GenerateWithoutReference(token, schema, rootSchema, typeNameHint); } - private void GenerateWithoutReference(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema, string typeNameHint) + private void GenerateWithoutReference(JToken token, JsonSchema schema, JsonSchema rootSchema, string typeNameHint) { if (token == null) return; @@ -132,12 +132,12 @@ private void GenerateWithoutReference(JToken token, JsonSchema4 schema, JsonSche schema.Format = JsonFormatStrings.TimeSpan; } - private void GenerateObject(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema) + private void GenerateObject(JToken token, JsonSchema schema, JsonSchema rootSchema) { schema.Type = JsonObjectType.Object; foreach (var property in ((JObject)token).Properties()) { - var propertySchema = new JsonProperty(); + var propertySchema = new JsonSchemaProperty(); var propertyName = property.Value.Type == JTokenType.Array ? ConversionUtilities.Singularize(property.Name) : property.Name; var typeNameHint = ConversionUtilities.ConvertToUpperCamelCase(propertyName, true); @@ -146,29 +146,29 @@ private void GenerateObject(JToken token, JsonSchema4 schema, JsonSchema4 rootSc } } - private void GenerateArray(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema, string typeNameHint) + private void GenerateArray(JToken token, JsonSchema schema, JsonSchema rootSchema, string typeNameHint) { schema.Type = JsonObjectType.Array; var itemSchemas = ((JArray)token).Select(item => { - var itemSchema = new JsonSchema4(); + var itemSchema = new JsonSchema(); GenerateWithoutReference(item, itemSchema, rootSchema, typeNameHint); return itemSchema; }).ToList(); if (itemSchemas.Count == 0) - schema.Item = new JsonSchema4(); + schema.Item = new JsonSchema(); else if (itemSchemas.GroupBy(s => s.Type).Count() == 1) MergeAndAssignItemSchemas(rootSchema, schema, itemSchemas, typeNameHint); else schema.Item = itemSchemas.First(); } - private void MergeAndAssignItemSchemas(JsonSchema4 rootSchema, JsonSchema4 schema, List itemSchemas, string typeNameHint) + private void MergeAndAssignItemSchemas(JsonSchema rootSchema, JsonSchema schema, List itemSchemas, string typeNameHint) { var firstItemSchema = itemSchemas.First(); - var itemSchema = new JsonSchema4 + var itemSchema = new JsonSchema { Type = firstItemSchema.Type }; @@ -180,10 +180,10 @@ private void MergeAndAssignItemSchemas(JsonSchema4 rootSchema, JsonSchema4 schem } AddSchemaDefinition(rootSchema, itemSchema, typeNameHint); - schema.Item = new JsonSchema4 { Reference = itemSchema }; + schema.Item = new JsonSchema { Reference = itemSchema }; } - private void AddSchemaDefinition(JsonSchema4 rootSchema, JsonSchema4 schema, string typeNameHint) + private void AddSchemaDefinition(JsonSchema rootSchema, JsonSchema schema, string typeNameHint) { if (string.IsNullOrEmpty(typeNameHint) || rootSchema.Definitions.ContainsKey(typeNameHint)) { diff --git a/src/NJsonSchema/Generation/SchemaProcessorContext.cs b/src/NJsonSchema/Generation/SchemaProcessorContext.cs index 648a55021..6d299dc07 100644 --- a/src/NJsonSchema/Generation/SchemaProcessorContext.cs +++ b/src/NJsonSchema/Generation/SchemaProcessorContext.cs @@ -19,7 +19,7 @@ public class SchemaProcessorContext /// The resolver. /// The generator. /// The settings. - public SchemaProcessorContext(Type type, JsonSchema4 schema, JsonSchemaResolver resolver, JsonSchemaGenerator generator, JsonSchemaGeneratorSettings settings) + public SchemaProcessorContext(Type type, JsonSchema schema, JsonSchemaResolver resolver, JsonSchemaGenerator generator, JsonSchemaGeneratorSettings settings) { Type = type; Schema = schema; @@ -32,7 +32,7 @@ public SchemaProcessorContext(Type type, JsonSchema4 schema, JsonSchemaResolver public Type Type { get; } /// The JSON Schema to process. - public JsonSchema4 Schema { get; } + public JsonSchema Schema { get; } /// The JSON Schema resolver. public JsonSchemaResolver Resolver { get; } diff --git a/src/NJsonSchema/Generation/SchemaProcessors/DiscriminatorSchemaProcessor.cs b/src/NJsonSchema/Generation/SchemaProcessors/DiscriminatorSchemaProcessor.cs index b9a1c8bb4..c34b1ae5f 100644 --- a/src/NJsonSchema/Generation/SchemaProcessors/DiscriminatorSchemaProcessor.cs +++ b/src/NJsonSchema/Generation/SchemaProcessors/DiscriminatorSchemaProcessor.cs @@ -37,7 +37,7 @@ public async Task ProcessAsync(SchemaProcessorContext context) { var schema = context.Schema; schema.Discriminator = Discriminator; - schema.Properties[Discriminator] = new JsonProperty + schema.Properties[Discriminator] = new JsonSchemaProperty { Type = JsonObjectType.String, IsRequired = true diff --git a/src/NJsonSchema/Generation/TypeMappers/ITypeMapper.cs b/src/NJsonSchema/Generation/TypeMappers/ITypeMapper.cs index f2efbbadb..e530ca000 100644 --- a/src/NJsonSchema/Generation/TypeMappers/ITypeMapper.cs +++ b/src/NJsonSchema/Generation/TypeMappers/ITypeMapper.cs @@ -23,6 +23,6 @@ public interface ITypeMapper /// Gets the schema for the mapped type. /// The schema. /// The context. - Task GenerateSchemaAsync(JsonSchema4 schema, TypeMapperContext context); + Task GenerateSchemaAsync(JsonSchema schema, TypeMapperContext context); } } \ No newline at end of file diff --git a/src/NJsonSchema/Generation/TypeMappers/ObjectTypeMapper.cs b/src/NJsonSchema/Generation/TypeMappers/ObjectTypeMapper.cs index 29fd729d0..0192324f6 100644 --- a/src/NJsonSchema/Generation/TypeMappers/ObjectTypeMapper.cs +++ b/src/NJsonSchema/Generation/TypeMappers/ObjectTypeMapper.cs @@ -14,12 +14,12 @@ namespace NJsonSchema.Generation.TypeMappers /// Maps .NET type to a generated JSON Schema describing an object. public class ObjectTypeMapper : ITypeMapper { - private readonly Func> _schemaFactory; + private readonly Func> _schemaFactory; /// Initializes a new instance of the class. /// Type of the mapped. /// The schema. - public ObjectTypeMapper(Type mappedType, JsonSchema4 schema) + public ObjectTypeMapper(Type mappedType, JsonSchema schema) : this(mappedType, (schemaGenerator, schemaResolver) => schema) { } @@ -27,7 +27,7 @@ public ObjectTypeMapper(Type mappedType, JsonSchema4 schema) /// Initializes a new instance of the class. /// Type of the mapped. /// The schema factory. - public ObjectTypeMapper(Type mappedType, Func schemaFactory) + public ObjectTypeMapper(Type mappedType, Func schemaFactory) #pragma warning disable 1998 : this(mappedType, async (schemaGenerator, schemaResolver) => schemaFactory(schemaGenerator, schemaResolver)) #pragma warning restore 1998 @@ -37,7 +37,7 @@ public ObjectTypeMapper(Type mappedType, FuncInitializes a new instance of the class. /// Type of the mapped. /// The schema factory. - public ObjectTypeMapper(Type mappedType, Func> schemaFactory) + public ObjectTypeMapper(Type mappedType, Func> schemaFactory) { _schemaFactory = schemaFactory; MappedType = mappedType; @@ -53,7 +53,7 @@ public ObjectTypeMapper(Type mappedType, FuncThe schema. /// The context. #pragma warning disable 1998 - public async Task GenerateSchemaAsync(JsonSchema4 schema, TypeMapperContext context) + public async Task GenerateSchemaAsync(JsonSchema schema, TypeMapperContext context) #pragma warning restore 1998 { if (!context.JsonSchemaResolver.HasSchema(MappedType, false)) diff --git a/src/NJsonSchema/Generation/TypeMappers/PrimitiveTypeMapper.cs b/src/NJsonSchema/Generation/TypeMappers/PrimitiveTypeMapper.cs index 1c6782067..1e0d6c724 100644 --- a/src/NJsonSchema/Generation/TypeMappers/PrimitiveTypeMapper.cs +++ b/src/NJsonSchema/Generation/TypeMappers/PrimitiveTypeMapper.cs @@ -14,12 +14,12 @@ namespace NJsonSchema.Generation.TypeMappers /// Maps .NET type to a generated JSON Schema describing a primitive value. public class PrimitiveTypeMapper : ITypeMapper { - private readonly Action _transformer; + private readonly Action _transformer; /// Initializes a new instance of the class. /// Type of the mapped. /// The transformer. - public PrimitiveTypeMapper(Type mappedType, Action transformer) + public PrimitiveTypeMapper(Type mappedType, Action transformer) { _transformer = transformer; MappedType = mappedType; @@ -35,7 +35,7 @@ public PrimitiveTypeMapper(Type mappedType, Action transformer) /// The schema. /// The context. #pragma warning disable 1998 - public async Task GenerateSchemaAsync(JsonSchema4 schema, TypeMapperContext context) + public async Task GenerateSchemaAsync(JsonSchema schema, TypeMapperContext context) #pragma warning restore 1998 { _transformer(schema); diff --git a/src/NJsonSchema/ITypeNameGenerator.cs b/src/NJsonSchema/ITypeNameGenerator.cs index db604b367..a98fd951b 100644 --- a/src/NJsonSchema/ITypeNameGenerator.cs +++ b/src/NJsonSchema/ITypeNameGenerator.cs @@ -10,7 +10,7 @@ namespace NJsonSchema { - /// Generates the type name for a given . + /// Generates the type name for a given . public interface ITypeNameGenerator { /// Generates the type name. @@ -18,6 +18,6 @@ public interface ITypeNameGenerator /// The type name hint (the property name or definition key). /// The reserved type names. /// The new name. - string Generate(JsonSchema4 schema, string typeNameHint, IEnumerable reservedTypeNames); + string Generate(JsonSchema schema, string typeNameHint, IEnumerable reservedTypeNames); } } \ No newline at end of file diff --git a/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs b/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs index d362ce060..5551d6c00 100644 --- a/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs +++ b/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs @@ -10,12 +10,13 @@ using System.Reflection; using Namotion.Reflection; using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; namespace NJsonSchema.Infrastructure { internal class IgnoreEmptyCollectionsContractResolver : PropertyRenameAndIgnoreSerializerContractResolver { - protected override Newtonsoft.Json.Serialization.JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); diff --git a/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs b/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs index 212b0a8c9..433f98124 100644 --- a/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs +++ b/src/NJsonSchema/Infrastructure/PropertyRenameAndIgnoreSerializerContractResolver.cs @@ -51,11 +51,11 @@ public void RenameProperty(Type type, string propertyName, string newJsonPropert _renames[type.FullName][propertyName] = newJsonPropertyName; } - /// Creates a Newtonsoft.Json.Serialization.JsonProperty for the given System.Reflection.MemberInfo. + /// Creates a JsonProperty for the given System.Reflection.MemberInfo. /// The member's parent Newtonsoft.Json.MemberSerialization. - /// The member to create a Newtonsoft.Json.Serialization.JsonProperty for. - /// A created Newtonsoft.Json.Serialization.JsonProperty for the given System.Reflection.MemberInfo. - protected override Newtonsoft.Json.Serialization.JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) + /// The member to create a JsonProperty for. + /// A created JsonProperty for the given System.Reflection.MemberInfo. + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); diff --git a/src/NJsonSchema/Infrastructure/XmlObjectExtension.cs b/src/NJsonSchema/Infrastructure/XmlObjectExtension.cs index 892bd9e6a..2d1a00f00 100644 --- a/src/NJsonSchema/Infrastructure/XmlObjectExtension.cs +++ b/src/NJsonSchema/Infrastructure/XmlObjectExtension.cs @@ -20,7 +20,7 @@ public static class XmlObjectExtension /// Generate XML object for a JSON Schema definition. /// The JSON Schema. /// The type of the JSON Schema. - public static void GenerateXmlObjectForType(this JsonSchema4 schema, Type type) + public static void GenerateXmlObjectForType(this JsonSchema schema, Type type) { var attributes = type.ToCachedType().TypeAttributes; if (attributes.Any()) @@ -33,7 +33,7 @@ public static void GenerateXmlObjectForType(this JsonSchema4 schema, Type type) /// Generates an XML object for a JSON Schema definition. /// The JSON Schema - public static void GenerateXmlObjectForArrayType(this JsonSchema4 schema) + public static void GenerateXmlObjectForArrayType(this JsonSchema schema) { if (schema.IsArray && schema.ParentSchema == null) { @@ -44,7 +44,7 @@ public static void GenerateXmlObjectForArrayType(this JsonSchema4 schema) /// Generates XMLObject structure for an array with primitive types /// The JSON Schema of the item. /// The item type. - public static void GenerateXmlObjectForItemType(this JsonSchema4 schema, CachedType type) + public static void GenerateXmlObjectForItemType(this JsonSchema schema, CachedType type) { // Is done all the time for XML to be able to get type name as the element name if not there was an attribute defined since earlier var attributes = type.TypeAttributes; @@ -63,7 +63,7 @@ public static void GenerateXmlObjectForItemType(this JsonSchema4 schema, CachedT /// The JSON Schema for the property /// The type. /// The property name. - public static void GenerateXmlObjectForProperty(this JsonProperty propertySchema, ContextualType type, string propertyName) + public static void GenerateXmlObjectForProperty(this JsonSchemaProperty propertySchema, ContextualType type, string propertyName) { string xmlName = null; string xmlNamespace = null; @@ -121,7 +121,7 @@ public static void GenerateXmlObjectForProperty(this JsonProperty propertySchema GenerateXmlObject(xmlName, xmlNamespace, xmlWrapped, xmlAttribute != null ? true : false, propertySchema); } - private static void GenerateXmlObject(string name, string @namespace, bool wrapped, bool isAttribute, JsonSchema4 schema) + private static void GenerateXmlObject(string name, string @namespace, bool wrapped, bool isAttribute, JsonSchema schema) { schema.Xml = new JsonXmlObject { diff --git a/src/NJsonSchema/JsonExtensionObject.cs b/src/NJsonSchema/JsonExtensionObject.cs index a593700eb..3981aad31 100644 --- a/src/NJsonSchema/JsonExtensionObject.cs +++ b/src/NJsonSchema/JsonExtensionObject.cs @@ -77,7 +77,7 @@ private object TryDeserializeValueSchemas(object value, JsonSerializer serialize { try { - return obj.ToObject(serializer); + return obj.ToObject(serializer); } catch { diff --git a/src/NJsonSchema/JsonReferenceResolver.cs b/src/NJsonSchema/JsonReferenceResolver.cs index 672a9159d..6abd57ae7 100644 --- a/src/NJsonSchema/JsonReferenceResolver.cs +++ b/src/NJsonSchema/JsonReferenceResolver.cs @@ -35,9 +35,9 @@ public JsonReferenceResolver(JsonSchemaAppender schemaAppender) /// Creates the factory to be used in the FromJsonAsync method. /// The type name generator. /// The factory. - public static Func CreateJsonReferenceResolverFactory(ITypeNameGenerator typeNameGenerator) + public static Func CreateJsonReferenceResolverFactory(ITypeNameGenerator typeNameGenerator) { - JsonReferenceResolver ReferenceResolverFactory(JsonSchema4 schema) => + JsonReferenceResolver ReferenceResolverFactory(JsonSchema schema) => new JsonReferenceResolver(new JsonSchemaAppender(schema, typeNameGenerator)); return ReferenceResolverFactory; @@ -93,7 +93,7 @@ public virtual IJsonReference ResolveDocumentReference(object rootObject, string /// The System.IO.File API is not available on this platform. public virtual async Task ResolveFileReferenceAsync(string filePath) { - return await JsonSchema4.FromFileAsync(filePath, schema => this).ConfigureAwait(false); + return await JsonSchema.FromFileAsync(filePath, schema => this).ConfigureAwait(false); } /// Resolves an URL reference. @@ -101,7 +101,7 @@ public virtual async Task ResolveFileReferenceAsync(string fileP /// The HttpClient.GetAsync API is not available on this platform. public virtual async Task ResolveUrlReferenceAsync(string url) { - return await JsonSchema4.FromUrlAsync(url, schema => this).ConfigureAwait(false); + return await JsonSchema.FromUrlAsync(url, schema => this).ConfigureAwait(false); } private async Task ResolveReferenceAsync(object rootObject, string jsonPath, bool append) @@ -157,11 +157,11 @@ private async Task ResolveFileReferenceWithAlreadyResolvedCheckA var referencedFile = _resolvedObjects[filePath]; var resolvedSchema = arr.Length == 1 ? referencedFile : await ResolveReferenceAsync(referencedFile, arr[1]).ConfigureAwait(false); - if (resolvedSchema is JsonSchema4 && append && - (_schemaAppender.RootObject as JsonSchema4)?.Definitions.Values.Contains(referencedFile) != true) + if (resolvedSchema is JsonSchema && append && + (_schemaAppender.RootObject as JsonSchema)?.Definitions.Values.Contains(referencedFile) != true) { var key = jsonPath.Split('/', '\\').Last().Split('.').First(); - _schemaAppender.AppendSchema((JsonSchema4)resolvedSchema, key); + _schemaAppender.AppendSchema((JsonSchema)resolvedSchema, key); } return resolvedSchema; @@ -181,9 +181,9 @@ private async Task ResolveUrlReferenceWithAlreadyResolvedCheckAs { var schema = await ResolveUrlReferenceAsync(arr[0]).ConfigureAwait(false); schema.DocumentPath = jsonPath; - if (schema is JsonSchema4 && append) + if (schema is JsonSchema && append) { - _schemaAppender.AppendSchema((JsonSchema4)schema, null); + _schemaAppender.AppendSchema((JsonSchema)schema, null); } _resolvedObjects[arr[0]] = schema; diff --git a/src/NJsonSchema/JsonSchema4.Reference.cs b/src/NJsonSchema/JsonSchema.Reference.cs similarity index 95% rename from src/NJsonSchema/JsonSchema4.Reference.cs rename to src/NJsonSchema/JsonSchema.Reference.cs index 8f928d744..88c4e3f25 100644 --- a/src/NJsonSchema/JsonSchema4.Reference.cs +++ b/src/NJsonSchema/JsonSchema.Reference.cs @@ -16,19 +16,19 @@ namespace NJsonSchema { - public partial class JsonSchema4 : JsonReferenceBase, IJsonReference + public partial class JsonSchema : JsonReferenceBase, IJsonReference { /// Gets the actual schema, either this or the referenced schema. /// Cyclic references detected. /// The schema reference path has not been resolved. [JsonIgnore] - public virtual JsonSchema4 ActualSchema => GetActualSchema(new List()); + public virtual JsonSchema ActualSchema => GetActualSchema(new List()); /// Gets the type actual schema (e.g. the shared schema of a property, parameter, etc.). /// Cyclic references detected. /// The schema reference path has not been resolved. [JsonIgnore] - public virtual JsonSchema4 ActualTypeSchema + public virtual JsonSchema ActualTypeSchema { get { @@ -90,7 +90,7 @@ public virtual JsonSchema4 ActualTypeSchema /// Cyclic references detected. /// The schema reference path has not been resolved. - private JsonSchema4 GetActualSchema(IList checkedSchemas) + private JsonSchema GetActualSchema(IList checkedSchemas) { if (checkedSchemas.Contains(this)) throw new InvalidOperationException("Cyclic references detected."); @@ -129,7 +129,7 @@ private JsonSchema4 GetActualSchema(IList checkedSchemas) /// Gets or sets the referenced object. [JsonIgnore] - public override JsonSchema4 Reference + public override JsonSchema Reference { get { return base.Reference; } set diff --git a/src/NJsonSchema/JsonSchema4.Serialization.cs b/src/NJsonSchema/JsonSchema.Serialization.cs similarity index 82% rename from src/NJsonSchema/JsonSchema4.Serialization.cs rename to src/NJsonSchema/JsonSchema.Serialization.cs index 1aafa315b..23bdc042d 100644 --- a/src/NJsonSchema/JsonSchema4.Serialization.cs +++ b/src/NJsonSchema/JsonSchema.Serialization.cs @@ -1,412 +1,412 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) Rico Suter. All rights reserved. -// -// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md -// Rico Suter, mail@rsuter.com -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Linq; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NJsonSchema.Collections; -using NJsonSchema.Infrastructure; - -namespace NJsonSchema -{ - [JsonConverter(typeof(ExtensionDataDeserializationConverter))] - public partial class JsonSchema4 : IJsonExtensionObject - { - private static JsonObjectType[] _jsonObjectTypeValues = Enum.GetValues(typeof(JsonObjectType)) - .OfType() - .Where(v => v != JsonObjectType.None) - .ToArray(); - - /// Creates the serializer contract resolver based on the . - /// The schema type. - /// The settings. - public static PropertyRenameAndIgnoreSerializerContractResolver CreateJsonSerializerContractResolver(SchemaType schemaType) - { - var resolver = new IgnoreEmptyCollectionsContractResolver(); - - if (schemaType == SchemaType.OpenApi3) - { - resolver.RenameProperty(typeof(JsonProperty), "x-readOnly", "readOnly"); - resolver.RenameProperty(typeof(JsonProperty), "x-writeOnly", "writeOnly"); - - resolver.RenameProperty(typeof(JsonSchema4), "x-nullable", "nullable"); - resolver.RenameProperty(typeof(JsonSchema4), "x-example", "example"); - } - else if (schemaType == SchemaType.Swagger2) - { - resolver.RenameProperty(typeof(JsonProperty), "x-readOnly", "readOnly"); - resolver.RenameProperty(typeof(JsonSchema4), "x-example", "example"); - } - else - { - resolver.RenameProperty(typeof(JsonProperty), "x-readOnly", "readonly"); - } - - return resolver; - } - - /// Gets or sets the extension data (i.e. additional properties which are not directly defined by JSON Schema). - [JsonExtensionData] - public IDictionary ExtensionData { get; set; } - - [OnDeserialized] - internal void OnDeserialized(StreamingContext ctx) - { - Initialize(); - } - - /// Gets the discriminator property (Swagger only). - [JsonIgnore] - public string ActualDiscriminator => ActualTypeSchema.Discriminator; - - /// Gets or sets the discriminator property (Swagger only, should not be used in internal tooling). - [JsonIgnore] - public string Discriminator - { - get => DiscriminatorObject?.PropertyName; - set - { - if (!string.IsNullOrEmpty(value)) - { - DiscriminatorObject = new OpenApiDiscriminator - { - PropertyName = value - }; - } - else - { - DiscriminatorObject = null; - } - } - } - - /// Gets the actual resolved discriminator of this schema (no inheritance, OpenApi only). - [JsonIgnore] - public OpenApiDiscriminator ActualDiscriminatorObject => DiscriminatorObject ?? ActualTypeSchema.DiscriminatorObject; - - /// Gets or sets the discriminator of this schema (OpenApi only). - [JsonIgnore] - public OpenApiDiscriminator DiscriminatorObject { get; set; } - - /// Gets or sets the discriminator. - [JsonProperty("discriminator", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 5)] - internal object DiscriminatorRaw - { - get - { - if (JsonSchemaSerialization.CurrentSchemaType != SchemaType.Swagger2) - return DiscriminatorObject; - else - return Discriminator; - } - set - { - if (value is string) - Discriminator = (string)value; - else if (value != null) - DiscriminatorObject = ((JObject)value).ToObject(); - } - } - - /// Gets or sets the enumeration names (optional, draft v5). - [JsonIgnore] - public Collection EnumerationNames { get; set; } - - /// Gets or sets a value indicating whether the maximum value is excluded. - [JsonProperty("exclusiveMaximum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal object ExclusiveMaximumRaw - { - get { return ExclusiveMaximum ?? (IsExclusiveMaximum ? (object)true : null); } - set - { - if (value is bool) - IsExclusiveMaximum = (bool)value; - else if (value != null && (value.Equals("true") || value.Equals("false"))) - IsExclusiveMaximum = value.Equals("true"); - else if (value != null) - ExclusiveMaximum = Convert.ToDecimal(value); - } - } - - /// Gets or sets a value indicating whether the minimum value is excluded. - [JsonProperty("exclusiveMinimum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal object ExclusiveMinimumRaw - { - get { return ExclusiveMinimum ?? (IsExclusiveMinimum ? (object)true : null); } - set - { - if (value is bool) - IsExclusiveMinimum = (bool)value; - else if (value != null && (value.Equals("true") || value.Equals("false"))) - IsExclusiveMinimum = value.Equals("true"); - else if (value != null) - ExclusiveMinimum = Convert.ToDecimal(value); - } - } - - [JsonProperty("additionalItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal object AdditionalItemsRaw - { - get - { - if (AdditionalItemsSchema != null) - return AdditionalItemsSchema; - if (!AllowAdditionalItems) - return false; - return null; - } - set - { - if (value is bool) - AllowAdditionalItems = (bool)value; - else if (value != null && (value.Equals("true") || value.Equals("false"))) - AllowAdditionalItems = value.Equals("true"); - else if (value != null) - AdditionalItemsSchema = FromJsonWithCurrentSettings(value); - } - } - - [JsonProperty("additionalProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal object AdditionalPropertiesRaw - { - get - { - if (AdditionalPropertiesSchema != null) - return AdditionalPropertiesSchema; - if (!AllowAdditionalProperties) - return false; - return null; - } - set - { - if (value is bool) - AllowAdditionalProperties = (bool)value; - else if (value != null && (value.Equals("true") || value.Equals("false"))) - AllowAdditionalProperties = value.Equals("true"); - else if (value != null) - AdditionalPropertiesSchema = FromJsonWithCurrentSettings(value); - } - } - - [JsonProperty("items", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal object ItemsRaw - { - get - { - if (Item != null) - return Item; - if (Items.Count > 0) - return Items; - return null; - } - set - { - if (value is JArray) - Items = new ObservableCollection(((JArray)value).Select(t => FromJsonWithCurrentSettings(t))); - else if (value != null) - Item = FromJsonWithCurrentSettings(value); - } - } - - private Lazy _typeRaw; - - [JsonProperty("type", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 3)] - internal object TypeRaw - { - get - { - if (_typeRaw == null) - ResetTypeRaw(); - - return _typeRaw.Value; - } - set - { - if (value is JArray) - Type = ((JArray)value).Aggregate(JsonObjectType.None, (type, token) => type | ConvertStringToJsonObjectType(token.ToString())); - else - Type = ConvertStringToJsonObjectType(value as string); - - ResetTypeRaw(); - } - } - - private void ResetTypeRaw() - { - _typeRaw = new Lazy(() => - { - var flags = _jsonObjectTypeValues - .Where(v => Type.HasFlag(v)) - .ToArray(); - - if (flags.Length > 1) - return new JArray(flags.Select(f => new JValue(f.ToString().ToLowerInvariant()))); - - if (flags.Length == 1) - return new JValue(flags[0].ToString().ToLowerInvariant()); - - return null; - }); - } - - [JsonProperty("required", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal ICollection RequiredPropertiesRaw - { - get { return RequiredProperties != null && RequiredProperties.Count > 0 ? RequiredProperties : null; } - set { RequiredProperties = value; } - } - - [JsonProperty("properties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal IDictionary PropertiesRaw - { - get => Properties != null && Properties.Count > 0 ? Properties : null; - set - { - Properties = value != null ? - new ObservableDictionary(value) : - new ObservableDictionary(); - } - } - - [JsonProperty("patternProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal IDictionary PatternPropertiesRaw - { - get - { - return PatternProperties != null && PatternProperties.Count > 0 ? - PatternProperties.ToDictionary(p => p.Key, p => p.Value) : null; - } - set - { - PatternProperties = value != null ? - new ObservableDictionary(value) : - new ObservableDictionary(); - } - } - - [JsonProperty("definitions", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal IDictionary DefinitionsRaw - { - get { return Definitions != null && Definitions.Count > 0 ? Definitions : null; } - set { Definitions = value != null ? new ObservableDictionary(value) : new ObservableDictionary(); } - } - - /// Gets or sets the enumeration names (optional, draft v5). - [JsonProperty("x-enumNames", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public Collection EnumerationNamesRaw - { - get { return EnumerationNames != null && EnumerationNames.Count > 0 ? EnumerationNames : null; } - set { EnumerationNames = value != null ? new ObservableCollection(value) : new ObservableCollection(); } - } - - [JsonProperty("enum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal ICollection EnumerationRaw - { - get { return Enumeration != null && Enumeration.Count > 0 ? Enumeration : null; } - set { Enumeration = value != null ? new ObservableCollection(value) : new ObservableCollection(); } - } - - [JsonProperty("allOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal ICollection AllOfRaw - { - get { return AllOf != null && AllOf.Count > 0 ? AllOf : null; } - set { AllOf = value != null ? new ObservableCollection(value) : new ObservableCollection(); } - } - - [JsonProperty("anyOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal ICollection AnyOfRaw - { - get { return AnyOf != null && AnyOf.Count > 0 ? AnyOf : null; } - set { AnyOf = value != null ? new ObservableCollection(value) : new ObservableCollection(); } - } - - [JsonProperty("oneOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - internal ICollection OneOfRaw - { - get { return OneOf != null && OneOf.Count > 0 ? OneOf : null; } - set { OneOf = value != null ? new ObservableCollection(value) : new ObservableCollection(); } - } - - private void RegisterProperties(IDictionary oldCollection, IDictionary newCollection) - { - if (oldCollection != null) - ((ObservableDictionary)oldCollection).CollectionChanged -= InitializeSchemaCollection; - - if (newCollection != null) - { - ((ObservableDictionary)newCollection).CollectionChanged += InitializeSchemaCollection; - InitializeSchemaCollection(newCollection, null); - } - } - - private void RegisterSchemaDictionary(IDictionary oldCollection, IDictionary newCollection) - where T : JsonSchema4 - { - if (oldCollection != null) - ((ObservableDictionary)oldCollection).CollectionChanged -= InitializeSchemaCollection; - - if (newCollection != null) - { - ((ObservableDictionary)newCollection).CollectionChanged += InitializeSchemaCollection; - InitializeSchemaCollection(newCollection, null); - } - } - - private void RegisterSchemaCollection(ICollection oldCollection, ICollection newCollection) - { - if (oldCollection != null) - ((ObservableCollection)oldCollection).CollectionChanged -= InitializeSchemaCollection; - - if (newCollection != null) - { - ((ObservableCollection)newCollection).CollectionChanged += InitializeSchemaCollection; - InitializeSchemaCollection(newCollection, null); - } - } - - private void InitializeSchemaCollection(object sender, NotifyCollectionChangedEventArgs e) - { - if (sender is ObservableDictionary) - { - var properties = (ObservableDictionary)sender; - foreach (var property in properties) - { - property.Value.Name = property.Key; - property.Value.Parent = this; - } - } - else if (sender is ObservableCollection) - { - var collection = (ObservableCollection)sender; - foreach (var item in collection) - item.Parent = this; - } - else if (sender is ObservableDictionary) - { - var collection = (ObservableDictionary)sender; - - foreach (var pair in collection.ToArray()) - { - if (pair.Value == null) - { - collection.Remove(pair.Key); - } - else - { - pair.Value.Parent = this; - } - } - } - } - } -} +//----------------------------------------------------------------------- +// +// Copyright (c) Rico Suter. All rights reserved. +// +// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md +// Rico Suter, mail@rsuter.com +//----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Linq; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using NJsonSchema.Collections; +using NJsonSchema.Infrastructure; + +namespace NJsonSchema +{ + [JsonConverter(typeof(ExtensionDataDeserializationConverter))] + public partial class JsonSchema : IJsonExtensionObject + { + private static JsonObjectType[] _jsonObjectTypeValues = Enum.GetValues(typeof(JsonObjectType)) + .OfType() + .Where(v => v != JsonObjectType.None) + .ToArray(); + + /// Creates the serializer contract resolver based on the . + /// The schema type. + /// The settings. + public static PropertyRenameAndIgnoreSerializerContractResolver CreateJsonSerializerContractResolver(SchemaType schemaType) + { + var resolver = new IgnoreEmptyCollectionsContractResolver(); + + if (schemaType == SchemaType.OpenApi3) + { + resolver.RenameProperty(typeof(JsonSchemaProperty), "x-readOnly", "readOnly"); + resolver.RenameProperty(typeof(JsonSchemaProperty), "x-writeOnly", "writeOnly"); + + resolver.RenameProperty(typeof(JsonSchema), "x-nullable", "nullable"); + resolver.RenameProperty(typeof(JsonSchema), "x-example", "example"); + } + else if (schemaType == SchemaType.Swagger2) + { + resolver.RenameProperty(typeof(JsonSchemaProperty), "x-readOnly", "readOnly"); + resolver.RenameProperty(typeof(JsonSchema), "x-example", "example"); + } + else + { + resolver.RenameProperty(typeof(JsonSchemaProperty), "x-readOnly", "readonly"); + } + + return resolver; + } + + /// Gets or sets the extension data (i.e. additional properties which are not directly defined by JSON Schema). + [JsonExtensionData] + public IDictionary ExtensionData { get; set; } + + [OnDeserialized] + internal void OnDeserialized(StreamingContext ctx) + { + Initialize(); + } + + /// Gets the discriminator property (Swagger only). + [JsonIgnore] + public string ActualDiscriminator => ActualTypeSchema.Discriminator; + + /// Gets or sets the discriminator property (Swagger only, should not be used in internal tooling). + [JsonIgnore] + public string Discriminator + { + get => DiscriminatorObject?.PropertyName; + set + { + if (!string.IsNullOrEmpty(value)) + { + DiscriminatorObject = new OpenApiDiscriminator + { + PropertyName = value + }; + } + else + { + DiscriminatorObject = null; + } + } + } + + /// Gets the actual resolved discriminator of this schema (no inheritance, OpenApi only). + [JsonIgnore] + public OpenApiDiscriminator ActualDiscriminatorObject => DiscriminatorObject ?? ActualTypeSchema.DiscriminatorObject; + + /// Gets or sets the discriminator of this schema (OpenApi only). + [JsonIgnore] + public OpenApiDiscriminator DiscriminatorObject { get; set; } + + /// Gets or sets the discriminator. + [JsonProperty("discriminator", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 5)] + internal object DiscriminatorRaw + { + get + { + if (JsonSchemaSerialization.CurrentSchemaType != SchemaType.Swagger2) + return DiscriminatorObject; + else + return Discriminator; + } + set + { + if (value is string) + Discriminator = (string)value; + else if (value != null) + DiscriminatorObject = ((JObject)value).ToObject(); + } + } + + /// Gets or sets the enumeration names (optional, draft v5). + [JsonIgnore] + public Collection EnumerationNames { get; set; } + + /// Gets or sets a value indicating whether the maximum value is excluded. + [JsonProperty("exclusiveMaximum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal object ExclusiveMaximumRaw + { + get { return ExclusiveMaximum ?? (IsExclusiveMaximum ? (object)true : null); } + set + { + if (value is bool) + IsExclusiveMaximum = (bool)value; + else if (value != null && (value.Equals("true") || value.Equals("false"))) + IsExclusiveMaximum = value.Equals("true"); + else if (value != null) + ExclusiveMaximum = Convert.ToDecimal(value); + } + } + + /// Gets or sets a value indicating whether the minimum value is excluded. + [JsonProperty("exclusiveMinimum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal object ExclusiveMinimumRaw + { + get { return ExclusiveMinimum ?? (IsExclusiveMinimum ? (object)true : null); } + set + { + if (value is bool) + IsExclusiveMinimum = (bool)value; + else if (value != null && (value.Equals("true") || value.Equals("false"))) + IsExclusiveMinimum = value.Equals("true"); + else if (value != null) + ExclusiveMinimum = Convert.ToDecimal(value); + } + } + + [JsonProperty("additionalItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal object AdditionalItemsRaw + { + get + { + if (AdditionalItemsSchema != null) + return AdditionalItemsSchema; + if (!AllowAdditionalItems) + return false; + return null; + } + set + { + if (value is bool) + AllowAdditionalItems = (bool)value; + else if (value != null && (value.Equals("true") || value.Equals("false"))) + AllowAdditionalItems = value.Equals("true"); + else if (value != null) + AdditionalItemsSchema = FromJsonWithCurrentSettings(value); + } + } + + [JsonProperty("additionalProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal object AdditionalPropertiesRaw + { + get + { + if (AdditionalPropertiesSchema != null) + return AdditionalPropertiesSchema; + if (!AllowAdditionalProperties) + return false; + return null; + } + set + { + if (value is bool) + AllowAdditionalProperties = (bool)value; + else if (value != null && (value.Equals("true") || value.Equals("false"))) + AllowAdditionalProperties = value.Equals("true"); + else if (value != null) + AdditionalPropertiesSchema = FromJsonWithCurrentSettings(value); + } + } + + [JsonProperty("items", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal object ItemsRaw + { + get + { + if (Item != null) + return Item; + if (Items.Count > 0) + return Items; + return null; + } + set + { + if (value is JArray) + Items = new ObservableCollection(((JArray)value).Select(t => FromJsonWithCurrentSettings(t))); + else if (value != null) + Item = FromJsonWithCurrentSettings(value); + } + } + + private Lazy _typeRaw; + + [JsonProperty("type", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 3)] + internal object TypeRaw + { + get + { + if (_typeRaw == null) + ResetTypeRaw(); + + return _typeRaw.Value; + } + set + { + if (value is JArray) + Type = ((JArray)value).Aggregate(JsonObjectType.None, (type, token) => type | ConvertStringToJsonObjectType(token.ToString())); + else + Type = ConvertStringToJsonObjectType(value as string); + + ResetTypeRaw(); + } + } + + private void ResetTypeRaw() + { + _typeRaw = new Lazy(() => + { + var flags = _jsonObjectTypeValues + .Where(v => Type.HasFlag(v)) + .ToArray(); + + if (flags.Length > 1) + return new JArray(flags.Select(f => new JValue(f.ToString().ToLowerInvariant()))); + + if (flags.Length == 1) + return new JValue(flags[0].ToString().ToLowerInvariant()); + + return null; + }); + } + + [JsonProperty("required", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal ICollection RequiredPropertiesRaw + { + get { return RequiredProperties != null && RequiredProperties.Count > 0 ? RequiredProperties : null; } + set { RequiredProperties = value; } + } + + [JsonProperty("properties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal IDictionary PropertiesRaw + { + get => Properties != null && Properties.Count > 0 ? Properties : null; + set + { + Properties = value != null ? + new ObservableDictionary(value) : + new ObservableDictionary(); + } + } + + [JsonProperty("patternProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal IDictionary PatternPropertiesRaw + { + get + { + return PatternProperties != null && PatternProperties.Count > 0 ? + PatternProperties.ToDictionary(p => p.Key, p => p.Value) : null; + } + set + { + PatternProperties = value != null ? + new ObservableDictionary(value) : + new ObservableDictionary(); + } + } + + [JsonProperty("definitions", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal IDictionary DefinitionsRaw + { + get { return Definitions != null && Definitions.Count > 0 ? Definitions : null; } + set { Definitions = value != null ? new ObservableDictionary(value) : new ObservableDictionary(); } + } + + /// Gets or sets the enumeration names (optional, draft v5). + [JsonProperty("x-enumNames", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public Collection EnumerationNamesRaw + { + get { return EnumerationNames != null && EnumerationNames.Count > 0 ? EnumerationNames : null; } + set { EnumerationNames = value != null ? new ObservableCollection(value) : new ObservableCollection(); } + } + + [JsonProperty("enum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal ICollection EnumerationRaw + { + get { return Enumeration != null && Enumeration.Count > 0 ? Enumeration : null; } + set { Enumeration = value != null ? new ObservableCollection(value) : new ObservableCollection(); } + } + + [JsonProperty("allOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal ICollection AllOfRaw + { + get { return AllOf != null && AllOf.Count > 0 ? AllOf : null; } + set { AllOf = value != null ? new ObservableCollection(value) : new ObservableCollection(); } + } + + [JsonProperty("anyOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal ICollection AnyOfRaw + { + get { return AnyOf != null && AnyOf.Count > 0 ? AnyOf : null; } + set { AnyOf = value != null ? new ObservableCollection(value) : new ObservableCollection(); } + } + + [JsonProperty("oneOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + internal ICollection OneOfRaw + { + get { return OneOf != null && OneOf.Count > 0 ? OneOf : null; } + set { OneOf = value != null ? new ObservableCollection(value) : new ObservableCollection(); } + } + + private void RegisterProperties(IDictionary oldCollection, IDictionary newCollection) + { + if (oldCollection != null) + ((ObservableDictionary)oldCollection).CollectionChanged -= InitializeSchemaCollection; + + if (newCollection != null) + { + ((ObservableDictionary)newCollection).CollectionChanged += InitializeSchemaCollection; + InitializeSchemaCollection(newCollection, null); + } + } + + private void RegisterSchemaDictionary(IDictionary oldCollection, IDictionary newCollection) + where T : JsonSchema + { + if (oldCollection != null) + ((ObservableDictionary)oldCollection).CollectionChanged -= InitializeSchemaCollection; + + if (newCollection != null) + { + ((ObservableDictionary)newCollection).CollectionChanged += InitializeSchemaCollection; + InitializeSchemaCollection(newCollection, null); + } + } + + private void RegisterSchemaCollection(ICollection oldCollection, ICollection newCollection) + { + if (oldCollection != null) + ((ObservableCollection)oldCollection).CollectionChanged -= InitializeSchemaCollection; + + if (newCollection != null) + { + ((ObservableCollection)newCollection).CollectionChanged += InitializeSchemaCollection; + InitializeSchemaCollection(newCollection, null); + } + } + + private void InitializeSchemaCollection(object sender, NotifyCollectionChangedEventArgs e) + { + if (sender is ObservableDictionary) + { + var properties = (ObservableDictionary)sender; + foreach (var property in properties) + { + property.Value.Name = property.Key; + property.Value.Parent = this; + } + } + else if (sender is ObservableCollection) + { + var collection = (ObservableCollection)sender; + foreach (var item in collection) + item.Parent = this; + } + else if (sender is ObservableDictionary) + { + var collection = (ObservableDictionary)sender; + + foreach (var pair in collection.ToArray()) + { + if (pair.Value == null) + { + collection.Remove(pair.Key); + } + else + { + pair.Value.Parent = this; + } + } + } + } + } +} diff --git a/src/NJsonSchema/JsonSchema4.cs b/src/NJsonSchema/JsonSchema.cs similarity index 84% rename from src/NJsonSchema/JsonSchema4.cs rename to src/NJsonSchema/JsonSchema.cs index 158d65b23..eaae69d94 100644 --- a/src/NJsonSchema/JsonSchema4.cs +++ b/src/NJsonSchema/JsonSchema.cs @@ -1,874 +1,874 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) Rico Suter. All rights reserved. -// -// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md -// Rico Suter, mail@rsuter.com -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Namotion.Reflection; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NJsonSchema.Collections; -using NJsonSchema.Generation; -using NJsonSchema.Infrastructure; -using NJsonSchema.Validation; - -namespace NJsonSchema -{ - /// A base class for describing a JSON schema. - public partial class JsonSchema4 : IDocumentPathProvider - { - private const SchemaType SerializationSchemaType = SchemaType.JsonSchema; - private static Lazy ContractResolver = new Lazy( - () => CreateJsonSerializerContractResolver(SerializationSchemaType)); - - private IDictionary _properties; - private IDictionary _patternProperties; - private IDictionary _definitions; - - private ICollection _allOf; - private ICollection _anyOf; - private ICollection _oneOf; - private JsonSchema4 _not; - private JsonSchema4 _dictionaryKey; - - private JsonSchema4 _item; - private ICollection _items; - - private bool _allowAdditionalItems = true; - private JsonSchema4 _additionalItemsSchema = null; - - private bool _allowAdditionalProperties = true; - private JsonSchema4 _additionalPropertiesSchema = null; - - /// Initializes a new instance of the class. - public JsonSchema4() - { - Initialize(); - } - - /// Creates a schema which matches any data. - /// The any schema. - public static JsonSchema4 CreateAnySchema() - { - return new JsonSchema4(); - } - - /// Creates a schema which matches any data. - /// The any schema. - public static TSchemaType CreateAnySchema() - where TSchemaType : JsonSchema4, new() - { - return new TSchemaType(); - } - - /// Gets the NJsonSchema toolchain version. -#if LEGACY - public static string ToolchainVersion => typeof(JsonSchema4).Assembly.GetName().Version + - " NET40 (Newtonsoft.Json v" + typeof(JToken).Assembly.GetName().Version + ")"; -#else - public static string ToolchainVersion => typeof(JsonSchema4).GetTypeInfo().Assembly.GetName().Version + - " (Newtonsoft.Json v" + typeof(JToken).GetTypeInfo().Assembly.GetName().Version + ")"; -#endif - - /// Creates a from a given type. - /// The type to create the schema for. - /// The . - public static async Task FromTypeAsync() - { - return await FromTypeAsync(new JsonSchemaGeneratorSettings()).ConfigureAwait(false); - } - - /// Creates a from a given type. - /// The type to create the schema for. - /// The . - public static async Task FromTypeAsync(Type type) - { - return await FromTypeAsync(type, new JsonSchemaGeneratorSettings()).ConfigureAwait(false); - } - - /// Creates a from a given type. - /// The type to create the schema for. - /// The settings. - /// The . - public static async Task FromTypeAsync(JsonSchemaGeneratorSettings settings) - { - var generator = new JsonSchemaGenerator(settings); - return await generator.GenerateAsync(typeof(TType)).ConfigureAwait(false); - } - - /// Creates a from a given type. - /// The type to create the schema for. - /// The settings. - /// The . - public static async Task FromTypeAsync(Type type, JsonSchemaGeneratorSettings settings) - { - var generator = new JsonSchemaGenerator(settings); - return await generator.GenerateAsync(type).ConfigureAwait(false); - } - - /// Creates a from sample JSON data. - /// The JSON Schema. - public static JsonSchema4 FromSampleJson(string data) - { - var generator = new SampleJsonSchemaGenerator(); - return generator.Generate(data); - } - - /// Loads a JSON Schema from a given file path (only available in .NET 4.x). - /// The file path. - /// The JSON Schema. - public static async Task FromFileAsync(string filePath) - { - var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator()); - return await FromFileAsync(filePath, factory).ConfigureAwait(false); - } - - /// Loads a JSON Schema from a given file path (only available in .NET 4.x). - /// The file path. - /// The JSON reference resolver factory. - /// The JSON Schema. - /// The System.IO.File API is not available on this platform. - public static async Task FromFileAsync(string filePath, Func referenceResolverFactory) - { - var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false); - return await FromJsonAsync(data, filePath, referenceResolverFactory).ConfigureAwait(false); - } - - /// Loads a JSON Schema from a given URL (only available in .NET 4.x). - /// The URL to the document. - /// The JSON Schema. - /// The HttpClient.GetAsync API is not available on this platform. - public static async Task FromUrlAsync(string url) - { - var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator()); - return await FromUrlAsync(url, factory).ConfigureAwait(false); - } - - /// Loads a JSON Schema from a given URL (only available in .NET 4.x). - /// The URL to the document. - /// The JSON reference resolver factory. - /// The JSON Schema. - /// The HttpClient.GetAsync API is not available on this platform. - public static async Task FromUrlAsync(string url, Func referenceResolverFactory) - { - var data = await DynamicApis.HttpGetAsync(url).ConfigureAwait(false); - return await FromJsonAsync(data, url, referenceResolverFactory).ConfigureAwait(false); - } - - /// Deserializes a JSON string to a . - /// The JSON string. - /// The JSON Schema. - public static async Task FromJsonAsync(string data) - { - return await FromJsonAsync(data, null).ConfigureAwait(false); - } - - /// Deserializes a JSON string to a . - /// The JSON string. - /// The document path (URL or file path) for resolving relative document references. - /// The JSON Schema. - public static async Task FromJsonAsync(string data, string documentPath) - { - var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator()); - return await FromJsonAsync(data, documentPath, factory).ConfigureAwait(false); - } - - /// Deserializes a JSON string to a . - /// The JSON string. - /// The document path (URL or file path) for resolving relative document references. - /// The JSON reference resolver factory. - /// The JSON Schema. - public static async Task FromJsonAsync(string data, string documentPath, Func referenceResolverFactory) - { - return await JsonSchemaSerialization.FromJsonAsync(data, SerializationSchemaType, documentPath, referenceResolverFactory, ContractResolver.Value).ConfigureAwait(false); - } - - internal static JsonSchema4 FromJsonWithCurrentSettings(object obj) - { - var json = JsonConvert.SerializeObject(obj, JsonSchemaSerialization.CurrentSerializerSettings); - return JsonConvert.DeserializeObject(json, JsonSchemaSerialization.CurrentSerializerSettings); - } - - /// Gets a value indicating whether the schema is binary (file or binary format). - [JsonIgnore] - public bool IsBinary - { - get - { - return Type.HasFlag(JsonObjectType.File) || - (Type.HasFlag(JsonObjectType.String) && Format == JsonFormatStrings.Binary); - } - } - - /// Gets the inherited/parent schema (most probable base schema in allOf). - /// Used for code generation. - [JsonIgnore] - public JsonSchema4 InheritedSchema - { - get - { - if (AllOf == null || AllOf.Count == 0 || HasReference) - return null; - - if (AllOf.Count == 1) - return AllOf.First().ActualSchema; - - if (AllOf.Any(s => s.HasReference && !s.ActualSchema.IsAnyType)) - return AllOf.First(s => s.HasReference && !s.ActualSchema.IsAnyType).ActualSchema; - - if (AllOf.Any(s => s.Type.HasFlag(JsonObjectType.Object) && !s.ActualSchema.IsAnyType)) - return AllOf.First(s => s.Type.HasFlag(JsonObjectType.Object) && !s.ActualSchema.IsAnyType).ActualSchema; - - return AllOf.First(s => !s.ActualSchema.IsAnyType)?.ActualSchema; - } - } - - /// Gets the inherited/parent schema which may also be inlined - /// (the schema itself if it is a dictionary or array, otherwise ). - /// Used for code generation. - [JsonIgnore] - public JsonSchema4 InheritedTypeSchema - { - get - { - if (ActualTypeSchema.IsDictionary || ActualTypeSchema.IsArray || ActualTypeSchema.IsTuple) - return ActualTypeSchema; - - return InheritedSchema; - } - } - - /// Gets the list of all inherited/parent schemas. - /// Used for code generation. - [JsonIgnore] -#if !LEGACY - public IReadOnlyCollection AllInheritedSchemas -#else - public ICollection AllInheritedSchemas -#endif - { - get - { - var inheritedSchema = this.InheritedSchema != null ? - new List { this.InheritedSchema } : - new List(); - - return inheritedSchema.Concat(inheritedSchema.SelectMany(s => s.AllInheritedSchemas)).ToList(); - } - } - - /// Determines whether the given schema is the parent schema of this schema (i.e. super/base class). - /// The possible subtype schema. - /// true or false - public bool Inherits(JsonSchema4 schema) - { - schema = schema.ActualSchema; - return InheritedSchema?.ActualSchema == schema || InheritedSchema?.Inherits(schema) == true; - } - - /// Gets the discriminator or discriminator of an inherited schema (or null). - [JsonIgnore] - public OpenApiDiscriminator ResponsibleDiscriminatorObject => - ActualDiscriminatorObject ?? InheritedSchema?.ActualSchema.ResponsibleDiscriminatorObject; - - /// Gets all properties of this schema (i.e. all direct properties and properties from the schemas in allOf which do not have a type). - /// Used for code generation. - /// Some properties are defined multiple times. - [JsonIgnore] -#if !LEGACY - public IReadOnlyDictionary ActualProperties -#else - public IDictionary ActualProperties -#endif - { - get - { - var properties = Properties - .Union(AllOf.Where(s => s.ActualSchema != InheritedSchema) - .SelectMany(s => s.ActualSchema.ActualProperties)) - .ToList(); - - var duplicatedProperties = properties - .GroupBy(p => p.Key) - .Where(g => g.Count() > 1) - .ToList(); - - if (duplicatedProperties.Any()) - throw new InvalidOperationException("The properties " + string.Join(", ", duplicatedProperties.Select(g => "'" + g.Key + "'")) + " are defined multiple times."); - -#if !LEGACY - return new ReadOnlyDictionary(properties.ToDictionary(p => p.Key, p => p.Value)); -#else - return new Dictionary(properties.ToDictionary(p => p.Key, p => p.Value)); -#endif - } - } - - /// Gets or sets the schema. - [JsonProperty("$schema", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 1)] - public string SchemaVersion { get; set; } - - /// Gets or sets the id. - [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 2)] - public string Id { get; set; } - - /// Gets or sets the title. - [JsonProperty("title", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 3)] - public string Title { get; set; } - - /// Gets a value indicating whether the schema title can be used as type name. - [JsonIgnore] - public bool HasTypeNameTitle => !string.IsNullOrEmpty(Title) && Regex.IsMatch(Title, "^[a-zA-Z0-9_]*$"); - - /// Gets or sets the description. - [JsonProperty("description", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public virtual string Description { get; set; } - - /// Gets the object types (as enum flags). - [JsonIgnore] - public JsonObjectType Type { get; set; } - - /// Gets the parent schema of this schema. - [JsonIgnore] - public JsonSchema4 ParentSchema => Parent as JsonSchema4; - - /// Gets the parent schema of this schema. - [JsonIgnore] - public virtual object Parent { get; set; } - - /// Gets or sets the format string. - [JsonProperty("format", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public string Format { get; set; } - - /// Gets or sets the default value. - [JsonProperty("default", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public object Default { get; set; } - - /// Gets or sets the required multiple of for the number value. - [JsonProperty("multipleOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public decimal? MultipleOf { get; set; } - - /// Gets or sets the maximum allowed value. - [JsonProperty("maximum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public decimal? Maximum { get; set; } - - /// Gets or sets the exclusive maximum value (v6). - [JsonIgnore] - public decimal? ExclusiveMaximum { get; set; } - - /// Gets or sets a value indicating whether the minimum value is excluded (v4). - [JsonIgnore] - public bool IsExclusiveMaximum { get; set; } - - /// Gets or sets the minimum allowed value. - [JsonProperty("minimum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public decimal? Minimum { get; set; } - - /// Gets or sets the exclusive minimum value (v6). - [JsonIgnore] - public decimal? ExclusiveMinimum { get; set; } - - /// Gets or sets a value indicating whether the minimum value is excluded (v4). - [JsonIgnore] - public bool IsExclusiveMinimum { get; set; } - - /// Gets or sets the maximum length of the value string. - [JsonProperty("maxLength", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public int? MaxLength { get; set; } - - /// Gets or sets the minimum length of the value string. - [JsonProperty("minLength", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public int? MinLength { get; set; } - - /// Gets or sets the validation pattern as regular expression. - [JsonProperty("pattern", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public string Pattern { get; set; } - - /// Gets or sets the maximum length of the array. - [JsonProperty("maxItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public int MaxItems { get; set; } - - /// Gets or sets the minimum length of the array. - [JsonProperty("minItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public int MinItems { get; set; } - - /// Gets or sets a value indicating whether the items in the array must be unique. - [JsonProperty("uniqueItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public bool UniqueItems { get; set; } - - /// Gets or sets the maximal number of allowed properties in an object. - [JsonProperty("maxProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public int MaxProperties { get; set; } - - /// Gets or sets the minimal number of allowed properties in an object. - [JsonProperty("minProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public int MinProperties { get; set; } - - /// Gets or sets a value indicating whether the schema is deprecated (Swagger and Open API only). - [JsonProperty("x-deprecated", DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool IsDeprecated { get; set; } - - /// Gets or sets a value indicating whether the type is abstract, i.e. cannot be instantiated directly (x-abstract). - [JsonProperty("x-abstract", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public bool IsAbstract { get; set; } - - /// Gets or sets a value indicating whether the schema is nullable (native in Open API 'nullable', custom in Swagger 'x-nullable'). - [JsonProperty("x-nullable", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public bool? IsNullableRaw { get; set; } - - /// Gets or sets the example (Swagger and Open API only). - [JsonProperty("x-example", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public object Example { get; set; } - - /// Gets or sets a value indicating this is an bit flag enum (custom extension, sets 'x-enumFlags', default: false). - [JsonProperty("x-enumFlags", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public bool IsFlagEnumerable { get; set; } - - /// Gets the collection of required properties. - [JsonIgnore] - public ICollection Enumeration { get; internal set; } - - /// Gets a value indicating whether this is enumeration. - [JsonIgnore] - public bool IsEnumeration => Enumeration.Count > 0; - - /// Gets the collection of required properties. - /// This collection can also be changed through the property. > - [JsonIgnore] - public ICollection RequiredProperties { get; internal set; } - - #region Child JSON schemas - - /// Gets or sets the dictionary key schema (x-key, only enum schemas are allowed). - [JsonProperty("x-dictionaryKey", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public JsonSchema4 DictionaryKey - { - get { return _dictionaryKey; } - set - { - _dictionaryKey = value; - if (_dictionaryKey != null) - _dictionaryKey.Parent = this; - } - } - - /// Gets the properties of the type. - [JsonIgnore] - public IDictionary Properties - { - get { return _properties; } - internal set - { - if (_properties != value) - { - RegisterProperties(_properties, value); - _properties = value; - } - } - } - - /// Gets the xml object of the schema (used in Swagger specifications). - [JsonProperty("xml", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public JsonXmlObject Xml - { - get { return _xmlObject; } - set - { - _xmlObject = value; - - if (_xmlObject != null) - _xmlObject.ParentSchema = this; - } - } - - [JsonIgnore] - private JsonXmlObject _xmlObject; - - /// Gets the pattern properties of the type. - [JsonIgnore] - public IDictionary PatternProperties - { - get { return _patternProperties; } - internal set - { - if (_patternProperties != value) - { - RegisterSchemaDictionary(_patternProperties, value); - _patternProperties = value; - } - } - } - - /// Gets or sets the schema of an array item. - [JsonIgnore] - public JsonSchema4 Item - { - get { return _item; } - set - { - if (_item != value) - { - _item = value; - if (_item != null) - { - _item.Parent = this; - Items.Clear(); - } - } - } - } - - /// Gets or sets the schemas of the array's tuple values. - [JsonIgnore] - public ICollection Items - { - get { return _items; } - internal set - { - if (_items != value) - { - RegisterSchemaCollection(_items, value); - _items = value; - - if (_items != null) - Item = null; - } - } - } - - /// Gets or sets the schema which must not be valid. - [JsonProperty("not", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - public JsonSchema4 Not - { - get { return _not; } - set - { - _not = value; - if (_not != null) - _not.Parent = this; - } - } - - /// Gets the other schema definitions of this schema. - [JsonIgnore] - public IDictionary Definitions - { - get { return _definitions; } - internal set - { - if (_definitions != value) - { - RegisterSchemaDictionary(_definitions, value); - _definitions = value; - } - } - } - - /// Gets the collection of schemas where each schema must be valid. - [JsonIgnore] - public ICollection AllOf - { - get { return _allOf; } - internal set - { - if (_allOf != value) - { - RegisterSchemaCollection(_allOf, value); - _allOf = value; - } - } - } - - /// Gets the collection of schemas where at least one must be valid. - [JsonIgnore] - public ICollection AnyOf - { - get { return _anyOf; } - internal set - { - if (_anyOf != value) - { - RegisterSchemaCollection(_anyOf, value); - _anyOf = value; - } - } - } - - /// Gets the collection of schemas where exactly one must be valid. - [JsonIgnore] - public ICollection OneOf - { - get { return _oneOf; } - internal set - { - if (_oneOf != value) - { - RegisterSchemaCollection(_oneOf, value); - _oneOf = value; - } - } - } - - /// Gets or sets a value indicating whether additional items are allowed (default: true). - /// If this property is set to false, then is set to null. - [JsonIgnore] - public bool AllowAdditionalItems - { - get { return _allowAdditionalItems; } - set - { - if (_allowAdditionalItems != value) - { - _allowAdditionalItems = value; - if (!_allowAdditionalItems) - AdditionalItemsSchema = null; - } - } - } - - /// Gets or sets the schema for the additional items. - /// If this property has a schema, then is set to true. - [JsonIgnore] - public JsonSchema4 AdditionalItemsSchema - { - get { return _additionalItemsSchema; } - set - { - if (_additionalItemsSchema != value) - { - _additionalItemsSchema = value; - if (_additionalItemsSchema != null) - AllowAdditionalItems = true; - } - } - } - - /// Gets or sets a value indicating whether additional properties are allowed (default: true). - /// If this property is set to false, then is set to null. - [JsonIgnore] - public bool AllowAdditionalProperties - { - get { return _allowAdditionalProperties; } - set - { - if (_allowAdditionalProperties != value) - { - _allowAdditionalProperties = value; - if (!_allowAdditionalProperties) - AdditionalPropertiesSchema = null; - } - } - } - - /// Gets or sets the schema for the additional properties. - /// If this property has a schema, then is set to true. - [JsonIgnore] - public JsonSchema4 AdditionalPropertiesSchema - { - get { return _additionalPropertiesSchema; } - set - { - if (_additionalPropertiesSchema != value) - { - _additionalPropertiesSchema = value; - if (_additionalPropertiesSchema != null) - AllowAdditionalProperties = true; - } - } - } - - /// Gets a value indicating whether the schema describes an object. - [JsonIgnore] - public bool IsObject => Type.HasFlag(JsonObjectType.Object); - - /// Gets a value indicating whether the schema represents an array type (an array where each item has the same type). - [JsonIgnore] - public bool IsArray => Type.HasFlag(JsonObjectType.Array) && (Items == null || Items.Count == 0); - - /// Gets a value indicating whether the schema represents an tuple type (an array where each item may have a different type). - [JsonIgnore] - public bool IsTuple => Type.HasFlag(JsonObjectType.Array) && Items?.Any() == true; - - /// Gets a value indicating whether the schema represents a dictionary type (no properties and AdditionalProperties or PatternProperties contain a schema). - [JsonIgnore] - public bool IsDictionary => Type.HasFlag(JsonObjectType.Object) && - ActualProperties.Count == 0 && - (AdditionalPropertiesSchema != null || PatternProperties.Any()); - - /// Gets a value indicating whether this is any type (e.g. any in TypeScript or object in CSharp). - [JsonIgnore] - public bool IsAnyType => (Type.HasFlag(JsonObjectType.Object) || Type == JsonObjectType.None) && - AllOf.Count == 0 && - AnyOf.Count == 0 && - OneOf.Count == 0 && - ActualProperties.Count == 0 && - PatternProperties.Count == 0 && - AllowAdditionalProperties && - AdditionalPropertiesSchema == null && - MultipleOf == null && - IsEnumeration == false; - - #endregion - - /// Gets a value indicating whether the validated data can be null. - /// The schema type. - /// true if the type can be null. - public virtual bool IsNullable(SchemaType schemaType) - { - if (IsNullableRaw == true) - return true; - - if (IsEnumeration && Enumeration.Contains(null)) - return true; - - if (Type.HasFlag(JsonObjectType.Null)) - return true; - - if ((Type == JsonObjectType.None || Type.HasFlag(JsonObjectType.Null)) && OneOf.Any(o => o.IsNullable(schemaType))) - return true; - - if (ActualSchema != this && ActualSchema.IsNullable(schemaType)) - return true; - - if (ActualTypeSchema != this && ActualTypeSchema.IsNullable(schemaType)) - return true; - - return false; - } - - /// Serializes the to a JSON string. - /// The JSON string. - public string ToJson() - { - return ToJson(Formatting.Indented); - } - - /// Serializes the to a JSON string. - /// The formatting. - /// The JSON string. - public string ToJson(Formatting formatting) - { - var oldSchema = SchemaVersion; - SchemaVersion = "http://json-schema.org/draft-04/schema#"; - - var json = JsonSchemaSerialization.ToJson(this, SerializationSchemaType, ContractResolver.Value, formatting); - - SchemaVersion = oldSchema; - return json; - } - - ///// Serializes the to a JSON string and removes externally loaded schemas. - ///// The JSON string. - //[Obsolete("Not ready yet as it has side-effects on the schema.")] - //public string ToJsonWithExternalReferences() - //{ - // // TODO: Copy "this" schema first (high-prio) - // var oldSchema = SchemaVersion; - // SchemaVersion = "http://json-schema.org/draft-04/schema#"; - // JsonSchemaReferenceUtilities.UpdateSchemaReferencePaths(this, true); - // var json = JsonSchemaReferenceUtilities.ConvertPropertyReferences(JsonConvert.SerializeObject(this, Formatting.Indented)); - // SchemaVersion = oldSchema; - // return json; - //} - - /// Gets a value indicating whether this schema inherits from the given parent schema. - /// The parent schema. - /// true or false. - public bool InheritsSchema(JsonSchema4 parentSchema) - { - return parentSchema != null && ActualSchema - .AllInheritedSchemas.Concat(new List { this }) - .Any(s => s.ActualSchema == parentSchema.ActualSchema) == true; - } - - /// Validates the given JSON data against this schema. - /// The JSON data to validate. - /// Could not deserialize the JSON data. - /// The collection of validation errors. - public ICollection Validate(string jsonData) - { - var validator = new JsonSchemaValidator(); - return validator.Validate(jsonData, ActualSchema); - } - - /// Validates the given JSON token against this schema. - /// The token to validate. - /// The collection of validation errors. - public ICollection Validate(JToken token) - { - var validator = new JsonSchemaValidator(); - return validator.Validate(token, ActualSchema); - } - - private static JsonObjectType ConvertStringToJsonObjectType(string value) - { - // Section 3.5: - // http://json-schema.org/latest/json-schema-core.html#anchor8 - // The string must be one of the 7 primitive types - - switch (value) - { - case "array": - return JsonObjectType.Array; - case "boolean": - return JsonObjectType.Boolean; - case "integer": - return JsonObjectType.Integer; - case "number": - return JsonObjectType.Number; - case "null": - return JsonObjectType.Null; - case "object": - return JsonObjectType.Object; - case "string": - return JsonObjectType.String; - case "file": // used for NSwag (special Swagger type) - return JsonObjectType.File; - default: - return JsonObjectType.None; - } - } - - private void Initialize() - { - if (Items == null) - Items = new ObservableCollection(); - - if (Properties == null) - Properties = new ObservableDictionary(); - - if (PatternProperties == null) - PatternProperties = new ObservableDictionary(); - - if (Definitions == null) - Definitions = new ObservableDictionary(); - - if (RequiredProperties == null) - RequiredProperties = new ObservableCollection(); - - if (AllOf == null) - AllOf = new ObservableCollection(); - - if (AnyOf == null) - AnyOf = new ObservableCollection(); - - if (OneOf == null) - OneOf = new ObservableCollection(); - - if (Enumeration == null) - Enumeration = new Collection(); - - if (EnumerationNames == null) - EnumerationNames = new Collection(); - } - } +//----------------------------------------------------------------------- +// +// Copyright (c) Rico Suter. All rights reserved. +// +// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md +// Rico Suter, mail@rsuter.com +//----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Namotion.Reflection; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using NJsonSchema.Collections; +using NJsonSchema.Generation; +using NJsonSchema.Infrastructure; +using NJsonSchema.Validation; + +namespace NJsonSchema +{ + /// A base class for describing a JSON schema. + public partial class JsonSchema : IDocumentPathProvider + { + private const SchemaType SerializationSchemaType = SchemaType.JsonSchema; + private static Lazy ContractResolver = new Lazy( + () => CreateJsonSerializerContractResolver(SerializationSchemaType)); + + private IDictionary _properties; + private IDictionary _patternProperties; + private IDictionary _definitions; + + private ICollection _allOf; + private ICollection _anyOf; + private ICollection _oneOf; + private JsonSchema _not; + private JsonSchema _dictionaryKey; + + private JsonSchema _item; + private ICollection _items; + + private bool _allowAdditionalItems = true; + private JsonSchema _additionalItemsSchema = null; + + private bool _allowAdditionalProperties = true; + private JsonSchema _additionalPropertiesSchema = null; + + /// Initializes a new instance of the class. + public JsonSchema() + { + Initialize(); + } + + /// Creates a schema which matches any data. + /// The any schema. + public static JsonSchema CreateAnySchema() + { + return new JsonSchema(); + } + + /// Creates a schema which matches any data. + /// The any schema. + public static TSchemaType CreateAnySchema() + where TSchemaType : JsonSchema, new() + { + return new TSchemaType(); + } + + /// Gets the NJsonSchema toolchain version. +#if LEGACY + public static string ToolchainVersion => typeof(JsonSchema).Assembly.GetName().Version + + " NET40 (Newtonsoft.Json v" + typeof(JToken).Assembly.GetName().Version + ")"; +#else + public static string ToolchainVersion => typeof(JsonSchema).GetTypeInfo().Assembly.GetName().Version + + " (Newtonsoft.Json v" + typeof(JToken).GetTypeInfo().Assembly.GetName().Version + ")"; +#endif + + /// Creates a from a given type. + /// The type to create the schema for. + /// The . + public static async Task FromTypeAsync() + { + return await FromTypeAsync(new JsonSchemaGeneratorSettings()).ConfigureAwait(false); + } + + /// Creates a from a given type. + /// The type to create the schema for. + /// The . + public static async Task FromTypeAsync(Type type) + { + return await FromTypeAsync(type, new JsonSchemaGeneratorSettings()).ConfigureAwait(false); + } + + /// Creates a from a given type. + /// The type to create the schema for. + /// The settings. + /// The . + public static async Task FromTypeAsync(JsonSchemaGeneratorSettings settings) + { + var generator = new JsonSchemaGenerator(settings); + return await generator.GenerateAsync(typeof(TType)).ConfigureAwait(false); + } + + /// Creates a from a given type. + /// The type to create the schema for. + /// The settings. + /// The . + public static async Task FromTypeAsync(Type type, JsonSchemaGeneratorSettings settings) + { + var generator = new JsonSchemaGenerator(settings); + return await generator.GenerateAsync(type).ConfigureAwait(false); + } + + /// Creates a from sample JSON data. + /// The JSON Schema. + public static JsonSchema FromSampleJson(string data) + { + var generator = new SampleJsonSchemaGenerator(); + return generator.Generate(data); + } + + /// Loads a JSON Schema from a given file path (only available in .NET 4.x). + /// The file path. + /// The JSON Schema. + public static async Task FromFileAsync(string filePath) + { + var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator()); + return await FromFileAsync(filePath, factory).ConfigureAwait(false); + } + + /// Loads a JSON Schema from a given file path (only available in .NET 4.x). + /// The file path. + /// The JSON reference resolver factory. + /// The JSON Schema. + /// The System.IO.File API is not available on this platform. + public static async Task FromFileAsync(string filePath, Func referenceResolverFactory) + { + var data = await DynamicApis.FileReadAllTextAsync(filePath).ConfigureAwait(false); + return await FromJsonAsync(data, filePath, referenceResolverFactory).ConfigureAwait(false); + } + + /// Loads a JSON Schema from a given URL (only available in .NET 4.x). + /// The URL to the document. + /// The JSON Schema. + /// The HttpClient.GetAsync API is not available on this platform. + public static async Task FromUrlAsync(string url) + { + var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator()); + return await FromUrlAsync(url, factory).ConfigureAwait(false); + } + + /// Loads a JSON Schema from a given URL (only available in .NET 4.x). + /// The URL to the document. + /// The JSON reference resolver factory. + /// The JSON Schema. + /// The HttpClient.GetAsync API is not available on this platform. + public static async Task FromUrlAsync(string url, Func referenceResolverFactory) + { + var data = await DynamicApis.HttpGetAsync(url).ConfigureAwait(false); + return await FromJsonAsync(data, url, referenceResolverFactory).ConfigureAwait(false); + } + + /// Deserializes a JSON string to a . + /// The JSON string. + /// The JSON Schema. + public static async Task FromJsonAsync(string data) + { + return await FromJsonAsync(data, null).ConfigureAwait(false); + } + + /// Deserializes a JSON string to a . + /// The JSON string. + /// The document path (URL or file path) for resolving relative document references. + /// The JSON Schema. + public static async Task FromJsonAsync(string data, string documentPath) + { + var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator()); + return await FromJsonAsync(data, documentPath, factory).ConfigureAwait(false); + } + + /// Deserializes a JSON string to a . + /// The JSON string. + /// The document path (URL or file path) for resolving relative document references. + /// The JSON reference resolver factory. + /// The JSON Schema. + public static async Task FromJsonAsync(string data, string documentPath, Func referenceResolverFactory) + { + return await JsonSchemaSerialization.FromJsonAsync(data, SerializationSchemaType, documentPath, referenceResolverFactory, ContractResolver.Value).ConfigureAwait(false); + } + + internal static JsonSchema FromJsonWithCurrentSettings(object obj) + { + var json = JsonConvert.SerializeObject(obj, JsonSchemaSerialization.CurrentSerializerSettings); + return JsonConvert.DeserializeObject(json, JsonSchemaSerialization.CurrentSerializerSettings); + } + + /// Gets a value indicating whether the schema is binary (file or binary format). + [JsonIgnore] + public bool IsBinary + { + get + { + return Type.HasFlag(JsonObjectType.File) || + (Type.HasFlag(JsonObjectType.String) && Format == JsonFormatStrings.Binary); + } + } + + /// Gets the inherited/parent schema (most probable base schema in allOf). + /// Used for code generation. + [JsonIgnore] + public JsonSchema InheritedSchema + { + get + { + if (AllOf == null || AllOf.Count == 0 || HasReference) + return null; + + if (AllOf.Count == 1) + return AllOf.First().ActualSchema; + + if (AllOf.Any(s => s.HasReference && !s.ActualSchema.IsAnyType)) + return AllOf.First(s => s.HasReference && !s.ActualSchema.IsAnyType).ActualSchema; + + if (AllOf.Any(s => s.Type.HasFlag(JsonObjectType.Object) && !s.ActualSchema.IsAnyType)) + return AllOf.First(s => s.Type.HasFlag(JsonObjectType.Object) && !s.ActualSchema.IsAnyType).ActualSchema; + + return AllOf.First(s => !s.ActualSchema.IsAnyType)?.ActualSchema; + } + } + + /// Gets the inherited/parent schema which may also be inlined + /// (the schema itself if it is a dictionary or array, otherwise ). + /// Used for code generation. + [JsonIgnore] + public JsonSchema InheritedTypeSchema + { + get + { + if (ActualTypeSchema.IsDictionary || ActualTypeSchema.IsArray || ActualTypeSchema.IsTuple) + return ActualTypeSchema; + + return InheritedSchema; + } + } + + /// Gets the list of all inherited/parent schemas. + /// Used for code generation. + [JsonIgnore] +#if !LEGACY + public IReadOnlyCollection AllInheritedSchemas +#else + public ICollection AllInheritedSchemas +#endif + { + get + { + var inheritedSchema = this.InheritedSchema != null ? + new List { this.InheritedSchema } : + new List(); + + return inheritedSchema.Concat(inheritedSchema.SelectMany(s => s.AllInheritedSchemas)).ToList(); + } + } + + /// Determines whether the given schema is the parent schema of this schema (i.e. super/base class). + /// The possible subtype schema. + /// true or false + public bool Inherits(JsonSchema schema) + { + schema = schema.ActualSchema; + return InheritedSchema?.ActualSchema == schema || InheritedSchema?.Inherits(schema) == true; + } + + /// Gets the discriminator or discriminator of an inherited schema (or null). + [JsonIgnore] + public OpenApiDiscriminator ResponsibleDiscriminatorObject => + ActualDiscriminatorObject ?? InheritedSchema?.ActualSchema.ResponsibleDiscriminatorObject; + + /// Gets all properties of this schema (i.e. all direct properties and properties from the schemas in allOf which do not have a type). + /// Used for code generation. + /// Some properties are defined multiple times. + [JsonIgnore] +#if !LEGACY + public IReadOnlyDictionary ActualProperties +#else + public IDictionary ActualProperties +#endif + { + get + { + var properties = Properties + .Union(AllOf.Where(s => s.ActualSchema != InheritedSchema) + .SelectMany(s => s.ActualSchema.ActualProperties)) + .ToList(); + + var duplicatedProperties = properties + .GroupBy(p => p.Key) + .Where(g => g.Count() > 1) + .ToList(); + + if (duplicatedProperties.Any()) + throw new InvalidOperationException("The properties " + string.Join(", ", duplicatedProperties.Select(g => "'" + g.Key + "'")) + " are defined multiple times."); + +#if !LEGACY + return new ReadOnlyDictionary(properties.ToDictionary(p => p.Key, p => p.Value)); +#else + return new Dictionary(properties.ToDictionary(p => p.Key, p => p.Value)); +#endif + } + } + + /// Gets or sets the schema. + [JsonProperty("$schema", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 1)] + public string SchemaVersion { get; set; } + + /// Gets or sets the id. + [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 2)] + public string Id { get; set; } + + /// Gets or sets the title. + [JsonProperty("title", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = -100 + 3)] + public string Title { get; set; } + + /// Gets a value indicating whether the schema title can be used as type name. + [JsonIgnore] + public bool HasTypeNameTitle => !string.IsNullOrEmpty(Title) && Regex.IsMatch(Title, "^[a-zA-Z0-9_]*$"); + + /// Gets or sets the description. + [JsonProperty("description", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public virtual string Description { get; set; } + + /// Gets the object types (as enum flags). + [JsonIgnore] + public JsonObjectType Type { get; set; } + + /// Gets the parent schema of this schema. + [JsonIgnore] + public JsonSchema ParentSchema => Parent as JsonSchema; + + /// Gets the parent schema of this schema. + [JsonIgnore] + public virtual object Parent { get; set; } + + /// Gets or sets the format string. + [JsonProperty("format", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public string Format { get; set; } + + /// Gets or sets the default value. + [JsonProperty("default", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public object Default { get; set; } + + /// Gets or sets the required multiple of for the number value. + [JsonProperty("multipleOf", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public decimal? MultipleOf { get; set; } + + /// Gets or sets the maximum allowed value. + [JsonProperty("maximum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public decimal? Maximum { get; set; } + + /// Gets or sets the exclusive maximum value (v6). + [JsonIgnore] + public decimal? ExclusiveMaximum { get; set; } + + /// Gets or sets a value indicating whether the minimum value is excluded (v4). + [JsonIgnore] + public bool IsExclusiveMaximum { get; set; } + + /// Gets or sets the minimum allowed value. + [JsonProperty("minimum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public decimal? Minimum { get; set; } + + /// Gets or sets the exclusive minimum value (v6). + [JsonIgnore] + public decimal? ExclusiveMinimum { get; set; } + + /// Gets or sets a value indicating whether the minimum value is excluded (v4). + [JsonIgnore] + public bool IsExclusiveMinimum { get; set; } + + /// Gets or sets the maximum length of the value string. + [JsonProperty("maxLength", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public int? MaxLength { get; set; } + + /// Gets or sets the minimum length of the value string. + [JsonProperty("minLength", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public int? MinLength { get; set; } + + /// Gets or sets the validation pattern as regular expression. + [JsonProperty("pattern", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public string Pattern { get; set; } + + /// Gets or sets the maximum length of the array. + [JsonProperty("maxItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public int MaxItems { get; set; } + + /// Gets or sets the minimum length of the array. + [JsonProperty("minItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public int MinItems { get; set; } + + /// Gets or sets a value indicating whether the items in the array must be unique. + [JsonProperty("uniqueItems", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public bool UniqueItems { get; set; } + + /// Gets or sets the maximal number of allowed properties in an object. + [JsonProperty("maxProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public int MaxProperties { get; set; } + + /// Gets or sets the minimal number of allowed properties in an object. + [JsonProperty("minProperties", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public int MinProperties { get; set; } + + /// Gets or sets a value indicating whether the schema is deprecated (Swagger and Open API only). + [JsonProperty("x-deprecated", DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool IsDeprecated { get; set; } + + /// Gets or sets a value indicating whether the type is abstract, i.e. cannot be instantiated directly (x-abstract). + [JsonProperty("x-abstract", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public bool IsAbstract { get; set; } + + /// Gets or sets a value indicating whether the schema is nullable (native in Open API 'nullable', custom in Swagger 'x-nullable'). + [JsonProperty("x-nullable", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public bool? IsNullableRaw { get; set; } + + /// Gets or sets the example (Swagger and Open API only). + [JsonProperty("x-example", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public object Example { get; set; } + + /// Gets or sets a value indicating this is an bit flag enum (custom extension, sets 'x-enumFlags', default: false). + [JsonProperty("x-enumFlags", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public bool IsFlagEnumerable { get; set; } + + /// Gets the collection of required properties. + [JsonIgnore] + public ICollection Enumeration { get; internal set; } + + /// Gets a value indicating whether this is enumeration. + [JsonIgnore] + public bool IsEnumeration => Enumeration.Count > 0; + + /// Gets the collection of required properties. + /// This collection can also be changed through the property. > + [JsonIgnore] + public ICollection RequiredProperties { get; internal set; } + + #region Child JSON schemas + + /// Gets or sets the dictionary key schema (x-key, only enum schemas are allowed). + [JsonProperty("x-dictionaryKey", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public JsonSchema DictionaryKey + { + get { return _dictionaryKey; } + set + { + _dictionaryKey = value; + if (_dictionaryKey != null) + _dictionaryKey.Parent = this; + } + } + + /// Gets the properties of the type. + [JsonIgnore] + public IDictionary Properties + { + get { return _properties; } + internal set + { + if (_properties != value) + { + RegisterProperties(_properties, value); + _properties = value; + } + } + } + + /// Gets the xml object of the schema (used in Swagger specifications). + [JsonProperty("xml", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public JsonXmlObject Xml + { + get { return _xmlObject; } + set + { + _xmlObject = value; + + if (_xmlObject != null) + _xmlObject.ParentSchema = this; + } + } + + [JsonIgnore] + private JsonXmlObject _xmlObject; + + /// Gets the pattern properties of the type. + [JsonIgnore] + public IDictionary PatternProperties + { + get { return _patternProperties; } + internal set + { + if (_patternProperties != value) + { + RegisterSchemaDictionary(_patternProperties, value); + _patternProperties = value; + } + } + } + + /// Gets or sets the schema of an array item. + [JsonIgnore] + public JsonSchema Item + { + get { return _item; } + set + { + if (_item != value) + { + _item = value; + if (_item != null) + { + _item.Parent = this; + Items.Clear(); + } + } + } + } + + /// Gets or sets the schemas of the array's tuple values. + [JsonIgnore] + public ICollection Items + { + get { return _items; } + internal set + { + if (_items != value) + { + RegisterSchemaCollection(_items, value); + _items = value; + + if (_items != null) + Item = null; + } + } + } + + /// Gets or sets the schema which must not be valid. + [JsonProperty("not", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + public JsonSchema Not + { + get { return _not; } + set + { + _not = value; + if (_not != null) + _not.Parent = this; + } + } + + /// Gets the other schema definitions of this schema. + [JsonIgnore] + public IDictionary Definitions + { + get { return _definitions; } + internal set + { + if (_definitions != value) + { + RegisterSchemaDictionary(_definitions, value); + _definitions = value; + } + } + } + + /// Gets the collection of schemas where each schema must be valid. + [JsonIgnore] + public ICollection AllOf + { + get { return _allOf; } + internal set + { + if (_allOf != value) + { + RegisterSchemaCollection(_allOf, value); + _allOf = value; + } + } + } + + /// Gets the collection of schemas where at least one must be valid. + [JsonIgnore] + public ICollection AnyOf + { + get { return _anyOf; } + internal set + { + if (_anyOf != value) + { + RegisterSchemaCollection(_anyOf, value); + _anyOf = value; + } + } + } + + /// Gets the collection of schemas where exactly one must be valid. + [JsonIgnore] + public ICollection OneOf + { + get { return _oneOf; } + internal set + { + if (_oneOf != value) + { + RegisterSchemaCollection(_oneOf, value); + _oneOf = value; + } + } + } + + /// Gets or sets a value indicating whether additional items are allowed (default: true). + /// If this property is set to false, then is set to null. + [JsonIgnore] + public bool AllowAdditionalItems + { + get { return _allowAdditionalItems; } + set + { + if (_allowAdditionalItems != value) + { + _allowAdditionalItems = value; + if (!_allowAdditionalItems) + AdditionalItemsSchema = null; + } + } + } + + /// Gets or sets the schema for the additional items. + /// If this property has a schema, then is set to true. + [JsonIgnore] + public JsonSchema AdditionalItemsSchema + { + get { return _additionalItemsSchema; } + set + { + if (_additionalItemsSchema != value) + { + _additionalItemsSchema = value; + if (_additionalItemsSchema != null) + AllowAdditionalItems = true; + } + } + } + + /// Gets or sets a value indicating whether additional properties are allowed (default: true). + /// If this property is set to false, then is set to null. + [JsonIgnore] + public bool AllowAdditionalProperties + { + get { return _allowAdditionalProperties; } + set + { + if (_allowAdditionalProperties != value) + { + _allowAdditionalProperties = value; + if (!_allowAdditionalProperties) + AdditionalPropertiesSchema = null; + } + } + } + + /// Gets or sets the schema for the additional properties. + /// If this property has a schema, then is set to true. + [JsonIgnore] + public JsonSchema AdditionalPropertiesSchema + { + get { return _additionalPropertiesSchema; } + set + { + if (_additionalPropertiesSchema != value) + { + _additionalPropertiesSchema = value; + if (_additionalPropertiesSchema != null) + AllowAdditionalProperties = true; + } + } + } + + /// Gets a value indicating whether the schema describes an object. + [JsonIgnore] + public bool IsObject => Type.HasFlag(JsonObjectType.Object); + + /// Gets a value indicating whether the schema represents an array type (an array where each item has the same type). + [JsonIgnore] + public bool IsArray => Type.HasFlag(JsonObjectType.Array) && (Items == null || Items.Count == 0); + + /// Gets a value indicating whether the schema represents an tuple type (an array where each item may have a different type). + [JsonIgnore] + public bool IsTuple => Type.HasFlag(JsonObjectType.Array) && Items?.Any() == true; + + /// Gets a value indicating whether the schema represents a dictionary type (no properties and AdditionalProperties or PatternProperties contain a schema). + [JsonIgnore] + public bool IsDictionary => Type.HasFlag(JsonObjectType.Object) && + ActualProperties.Count == 0 && + (AdditionalPropertiesSchema != null || PatternProperties.Any()); + + /// Gets a value indicating whether this is any type (e.g. any in TypeScript or object in CSharp). + [JsonIgnore] + public bool IsAnyType => (Type.HasFlag(JsonObjectType.Object) || Type == JsonObjectType.None) && + AllOf.Count == 0 && + AnyOf.Count == 0 && + OneOf.Count == 0 && + ActualProperties.Count == 0 && + PatternProperties.Count == 0 && + AllowAdditionalProperties && + AdditionalPropertiesSchema == null && + MultipleOf == null && + IsEnumeration == false; + + #endregion + + /// Gets a value indicating whether the validated data can be null. + /// The schema type. + /// true if the type can be null. + public virtual bool IsNullable(SchemaType schemaType) + { + if (IsNullableRaw == true) + return true; + + if (IsEnumeration && Enumeration.Contains(null)) + return true; + + if (Type.HasFlag(JsonObjectType.Null)) + return true; + + if ((Type == JsonObjectType.None || Type.HasFlag(JsonObjectType.Null)) && OneOf.Any(o => o.IsNullable(schemaType))) + return true; + + if (ActualSchema != this && ActualSchema.IsNullable(schemaType)) + return true; + + if (ActualTypeSchema != this && ActualTypeSchema.IsNullable(schemaType)) + return true; + + return false; + } + + /// Serializes the to a JSON string. + /// The JSON string. + public string ToJson() + { + return ToJson(Formatting.Indented); + } + + /// Serializes the to a JSON string. + /// The formatting. + /// The JSON string. + public string ToJson(Formatting formatting) + { + var oldSchema = SchemaVersion; + SchemaVersion = "http://json-schema.org/draft-04/schema#"; + + var json = JsonSchemaSerialization.ToJson(this, SerializationSchemaType, ContractResolver.Value, formatting); + + SchemaVersion = oldSchema; + return json; + } + + ///// Serializes the to a JSON string and removes externally loaded schemas. + ///// The JSON string. + //[Obsolete("Not ready yet as it has side-effects on the schema.")] + //public string ToJsonWithExternalReferences() + //{ + // // TODO: Copy "this" schema first (high-prio) + // var oldSchema = SchemaVersion; + // SchemaVersion = "http://json-schema.org/draft-04/schema#"; + // JsonSchemaReferenceUtilities.UpdateSchemaReferencePaths(this, true); + // var json = JsonSchemaReferenceUtilities.ConvertPropertyReferences(JsonConvert.SerializeObject(this, Formatting.Indented)); + // SchemaVersion = oldSchema; + // return json; + //} + + /// Gets a value indicating whether this schema inherits from the given parent schema. + /// The parent schema. + /// true or false. + public bool InheritsSchema(JsonSchema parentSchema) + { + return parentSchema != null && ActualSchema + .AllInheritedSchemas.Concat(new List { this }) + .Any(s => s.ActualSchema == parentSchema.ActualSchema) == true; + } + + /// Validates the given JSON data against this schema. + /// The JSON data to validate. + /// Could not deserialize the JSON data. + /// The collection of validation errors. + public ICollection Validate(string jsonData) + { + var validator = new JsonSchemaValidator(); + return validator.Validate(jsonData, ActualSchema); + } + + /// Validates the given JSON token against this schema. + /// The token to validate. + /// The collection of validation errors. + public ICollection Validate(JToken token) + { + var validator = new JsonSchemaValidator(); + return validator.Validate(token, ActualSchema); + } + + private static JsonObjectType ConvertStringToJsonObjectType(string value) + { + // Section 3.5: + // http://json-schema.org/latest/json-schema-core.html#anchor8 + // The string must be one of the 7 primitive types + + switch (value) + { + case "array": + return JsonObjectType.Array; + case "boolean": + return JsonObjectType.Boolean; + case "integer": + return JsonObjectType.Integer; + case "number": + return JsonObjectType.Number; + case "null": + return JsonObjectType.Null; + case "object": + return JsonObjectType.Object; + case "string": + return JsonObjectType.String; + case "file": // used for NSwag (special Swagger type) + return JsonObjectType.File; + default: + return JsonObjectType.None; + } + } + + private void Initialize() + { + if (Items == null) + Items = new ObservableCollection(); + + if (Properties == null) + Properties = new ObservableDictionary(); + + if (PatternProperties == null) + PatternProperties = new ObservableDictionary(); + + if (Definitions == null) + Definitions = new ObservableDictionary(); + + if (RequiredProperties == null) + RequiredProperties = new ObservableCollection(); + + if (AllOf == null) + AllOf = new ObservableCollection(); + + if (AnyOf == null) + AnyOf = new ObservableCollection(); + + if (OneOf == null) + OneOf = new ObservableCollection(); + + if (Enumeration == null) + Enumeration = new Collection(); + + if (EnumerationNames == null) + EnumerationNames = new Collection(); + } + } } \ No newline at end of file diff --git a/src/NJsonSchema/JsonSchemaAppender.cs b/src/NJsonSchema/JsonSchemaAppender.cs index b36558279..64d22d622 100644 --- a/src/NJsonSchema/JsonSchemaAppender.cs +++ b/src/NJsonSchema/JsonSchemaAppender.cs @@ -28,14 +28,14 @@ public JsonSchemaAppender(object rootObject, ITypeNameGenerator typeNameGenerato public object RootObject { get; } /// Gets the root schema. - protected JsonSchema4 RootSchema => (JsonSchema4)RootObject; + protected JsonSchema RootSchema => (JsonSchema)RootObject; /// Appends the schema to the root object. /// The schema to append. /// The type name hint. /// is /// The root schema cannot be appended. - public virtual void AppendSchema(JsonSchema4 schema, string typeNameHint) + public virtual void AppendSchema(JsonSchema schema, string typeNameHint) { if (schema == null) throw new ArgumentNullException(nameof(schema)); diff --git a/src/NJsonSchema/JsonProperty.cs b/src/NJsonSchema/JsonSchemaProperty.cs similarity index 93% rename from src/NJsonSchema/JsonProperty.cs rename to src/NJsonSchema/JsonSchemaProperty.cs index b5eb6cd7e..878e960eb 100644 --- a/src/NJsonSchema/JsonProperty.cs +++ b/src/NJsonSchema/JsonSchemaProperty.cs @@ -1,92 +1,92 @@ -//----------------------------------------------------------------------- -// -// Copyright (c) Rico Suter. All rights reserved. -// -// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md -// Rico Suter, mail@rsuter.com -//----------------------------------------------------------------------- - -using System.ComponentModel; -using Newtonsoft.Json; - -namespace NJsonSchema -{ - /// A description of a JSON property of a JSON object. - public class JsonProperty : JsonSchema4 // TODO: Rename to JsonSchemaProperty - { - private object _parent; - - /// Gets or sets the name of the property. - [JsonIgnore] - public string Name { get; internal set; } - - /// Gets the parent schema of this property schema. - [JsonIgnore] - public override object Parent - { - get { return _parent; } - set - { - var initialize = _parent == null; - _parent = value; - - if (initialize && InitialIsRequired) - IsRequired = InitialIsRequired; - } - } - - /// Gets or sets a value indicating whether the property is required. - [JsonIgnore] - public bool IsRequired - { - get { return ParentSchema.RequiredProperties.Contains(Name); } - set - { - if (ParentSchema == null) - InitialIsRequired = value; - else - { - if (value) - { - if (!ParentSchema.RequiredProperties.Contains(Name)) - ParentSchema.RequiredProperties.Add(Name); - } - else - { - if (ParentSchema.RequiredProperties.Contains(Name)) - ParentSchema.RequiredProperties.Remove(Name); - } - } - } - } - - /// Value used to set property even if parent is not set yet. - [JsonIgnore] - internal bool InitialIsRequired { get; set; } - - /// Gets or sets a value indicating whether the property is read only (Swagger and Open API only). - [DefaultValue(false)] - [JsonProperty("x-readOnly", DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool IsReadOnly { get; set; } - - /// Gets or sets a value indicating whether the property is write only (Open API only). - [DefaultValue(false)] - [JsonProperty("x-writeOnly", DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool IsWriteOnly { get; set; } - - /// Gets a value indicating whether the property is an inheritance discriminator. - [JsonIgnore] - public bool IsInheritanceDiscriminator => ParentSchema.ActualDiscriminator == Name; - - /// Determines whether the specified property null handling is nullable. - /// The schema type. - /// true if the type can be null. - public override bool IsNullable(SchemaType schemaType) - { - if (schemaType == SchemaType.Swagger2 && IsRequired == false) - return true; - - return base.IsNullable(schemaType); - } - } +//----------------------------------------------------------------------- +// +// Copyright (c) Rico Suter. All rights reserved. +// +// https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md +// Rico Suter, mail@rsuter.com +//----------------------------------------------------------------------- + +using System.ComponentModel; +using Newtonsoft.Json; + +namespace NJsonSchema +{ + /// A description of a JSON property of a JSON schema. + public class JsonSchemaProperty : JsonSchema + { + private object _parent; + + /// Gets or sets the name of the property. + [JsonIgnore] + public string Name { get; internal set; } + + /// Gets the parent schema of this property schema. + [JsonIgnore] + public override object Parent + { + get { return _parent; } + set + { + var initialize = _parent == null; + _parent = value; + + if (initialize && InitialIsRequired) + IsRequired = InitialIsRequired; + } + } + + /// Gets or sets a value indicating whether the property is required. + [JsonIgnore] + public bool IsRequired + { + get { return ParentSchema.RequiredProperties.Contains(Name); } + set + { + if (ParentSchema == null) + InitialIsRequired = value; + else + { + if (value) + { + if (!ParentSchema.RequiredProperties.Contains(Name)) + ParentSchema.RequiredProperties.Add(Name); + } + else + { + if (ParentSchema.RequiredProperties.Contains(Name)) + ParentSchema.RequiredProperties.Remove(Name); + } + } + } + } + + /// Value used to set property even if parent is not set yet. + [JsonIgnore] + internal bool InitialIsRequired { get; set; } + + /// Gets or sets a value indicating whether the property is read only (Swagger and Open API only). + [DefaultValue(false)] + [JsonProperty("x-readOnly", DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool IsReadOnly { get; set; } + + /// Gets or sets a value indicating whether the property is write only (Open API only). + [DefaultValue(false)] + [JsonProperty("x-writeOnly", DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool IsWriteOnly { get; set; } + + /// Gets a value indicating whether the property is an inheritance discriminator. + [JsonIgnore] + public bool IsInheritanceDiscriminator => ParentSchema.ActualDiscriminator == Name; + + /// Determines whether the specified property null handling is nullable. + /// The schema type. + /// true if the type can be null. + public override bool IsNullable(SchemaType schemaType) + { + if (schemaType == SchemaType.Swagger2 && IsRequired == false) + return true; + + return base.IsNullable(schemaType); + } + } } \ No newline at end of file diff --git a/src/NJsonSchema/JsonXmlObject.cs b/src/NJsonSchema/JsonXmlObject.cs index 99ceddc8e..53b314d0b 100644 --- a/src/NJsonSchema/JsonXmlObject.cs +++ b/src/NJsonSchema/JsonXmlObject.cs @@ -15,7 +15,7 @@ public class JsonXmlObject { /// Gets the parent schema of the XML object schema. [JsonIgnore] - public JsonSchema4 ParentSchema { get; internal set; } + public JsonSchema ParentSchema { get; internal set; } /// Gets or sets the name of the xml object. [JsonProperty("name", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] diff --git a/src/NJsonSchema/OpenApiDiscriminator.cs b/src/NJsonSchema/OpenApiDiscriminator.cs index d966762a4..544196fe6 100644 --- a/src/NJsonSchema/OpenApiDiscriminator.cs +++ b/src/NJsonSchema/OpenApiDiscriminator.cs @@ -26,7 +26,7 @@ public class OpenApiDiscriminator /// Gets or sets the discriminator mappings. [JsonProperty("mapping", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [JsonConverter(typeof(DiscriminatorMappingConverter))] - public IDictionary Mapping { get; } = new Dictionary(); + public IDictionary Mapping { get; } = new Dictionary(); /// The currently used . [JsonIgnore] @@ -35,7 +35,7 @@ public class OpenApiDiscriminator /// Adds a discriminator mapping for the given type and schema based on the used . /// The type. /// The schema. - public void AddMapping(Type type, JsonSchema4 schema) + public void AddMapping(Type type, JsonSchema schema) { dynamic converter = JsonInheritanceConverter; @@ -49,10 +49,10 @@ public void AddMapping(Type type, JsonSchema4 schema) if (getDiscriminatorValueMethod != null) { var discriminatorValue = converter.GetDiscriminatorValue(type); - Mapping[discriminatorValue] = new JsonSchema4 { Reference = schema.ActualSchema }; + Mapping[discriminatorValue] = new JsonSchema { Reference = schema.ActualSchema }; } else - Mapping[type.Name] = new JsonSchema4 { Reference = schema.ActualSchema }; + Mapping[type.Name] = new JsonSchema { Reference = schema.ActualSchema }; } /// @@ -72,12 +72,12 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist var openApiMapping = serializer.Deserialize>(reader); if (openApiMapping != null && existingValue != null) { - var internalMapping = (IDictionary)existingValue; + var internalMapping = (IDictionary)existingValue; internalMapping.Clear(); foreach (var tuple in openApiMapping) { - var schema = new JsonSchema4(); + var schema = new JsonSchema(); ((IJsonReferenceBase)schema).ReferencePath = tuple.Value; internalMapping[tuple.Key] = schema; } @@ -88,7 +88,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - var internalMapping = value as IDictionary; + var internalMapping = value as IDictionary; if (internalMapping != null) { var openApiMapping = new Dictionary(); diff --git a/src/NJsonSchema/Validation/ChildSchemaValidationError.cs b/src/NJsonSchema/Validation/ChildSchemaValidationError.cs index 1a09ac67c..0c0d7452c 100644 --- a/src/NJsonSchema/Validation/ChildSchemaValidationError.cs +++ b/src/NJsonSchema/Validation/ChildSchemaValidationError.cs @@ -22,9 +22,9 @@ public class ChildSchemaValidationError : ValidationError /// The token that failed to validate. /// The schema that contains the validation rule. #if !LEGACY - public ChildSchemaValidationError(ValidationErrorKind kind, string property, string path, IReadOnlyDictionary> errors, JToken token, JsonSchema4 schema) + public ChildSchemaValidationError(ValidationErrorKind kind, string property, string path, IReadOnlyDictionary> errors, JToken token, JsonSchema schema) #else - public ChildSchemaValidationError(ValidationErrorKind kind, string property, string path, IDictionary> errors, JToken token, JsonSchema4 schema) + public ChildSchemaValidationError(ValidationErrorKind kind, string property, string path, IDictionary> errors, JToken token, JsonSchema schema) #endif : base(kind, property, path, token, schema) { @@ -33,9 +33,9 @@ public ChildSchemaValidationError(ValidationErrorKind kind, string property, str /// Gets the errors for each validated subschema. #if !LEGACY - public IReadOnlyDictionary> Errors { get; private set; } + public IReadOnlyDictionary> Errors { get; private set; } #else - public IDictionary> Errors { get; private set; } + public IDictionary> Errors { get; private set; } #endif /// Returns a string that represents the current object. diff --git a/src/NJsonSchema/Validation/JsonSchemaValidator.cs b/src/NJsonSchema/Validation/JsonSchemaValidator.cs index fa8b724fc..b7630f718 100644 --- a/src/NJsonSchema/Validation/JsonSchemaValidator.cs +++ b/src/NJsonSchema/Validation/JsonSchemaValidator.cs @@ -51,7 +51,7 @@ public JsonSchemaValidator() /// The schema. /// Could not deserialize the JSON data. /// The list of validation errors. - public ICollection Validate(string jsonData, JsonSchema4 schema) + public ICollection Validate(string jsonData, JsonSchema schema) { using (var reader = new StringReader(jsonData)) using (var jsonReader = new JsonTextReader(reader) @@ -68,7 +68,7 @@ public ICollection Validate(string jsonData, JsonSchema4 schema /// The token. /// The schema. /// The list of validation errors. - public ICollection Validate(JToken token, JsonSchema4 schema) + public ICollection Validate(JToken token, JsonSchema schema) { return Validate(token, schema.ActualSchema, null, token.Path); } @@ -79,7 +79,7 @@ public ICollection Validate(JToken token, JsonSchema4 schema) /// The current property name. /// The current property path. /// The list of validation errors. - protected virtual ICollection Validate(JToken token, JsonSchema4 schema, string propertyName, string propertyPath) + protected virtual ICollection Validate(JToken token, JsonSchema schema, string propertyName, string propertyPath) { var errors = new List(); @@ -94,7 +94,7 @@ protected virtual ICollection Validate(JToken token, JsonSchema return errors; } - private void ValidateType(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateType(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { var types = GetTypes(schema).ToDictionary(t => t, t => (ICollection)new List()); if (types.Count > 1) @@ -135,12 +135,12 @@ private void ValidateType(JToken token, JsonSchema4 schema, string propertyName, .Where(t => t != JsonObjectType.None) .ToList(); - private IEnumerable GetTypes(JsonSchema4 schema) + private IEnumerable GetTypes(JsonSchema schema) { return JsonObjectTypes.Where(t => schema.Type.HasFlag(t)); } - private void ValidateAnyOf(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateAnyOf(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.AnyOf.Count > 0) { @@ -150,7 +150,7 @@ private void ValidateAnyOf(JToken token, JsonSchema4 schema, string propertyName } } - private void ValidateAllOf(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateAllOf(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.AllOf.Count > 0) { @@ -160,7 +160,7 @@ private void ValidateAllOf(JToken token, JsonSchema4 schema, string propertyName } } - private void ValidateOneOf(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateOneOf(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.OneOf.Count > 0) { @@ -170,7 +170,7 @@ private void ValidateOneOf(JToken token, JsonSchema4 schema, string propertyName } } - private void ValidateNot(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateNot(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.Not != null && Validate(token, schema.Not).Count == 0) { @@ -178,7 +178,7 @@ private void ValidateNot(JToken token, JsonSchema4 schema, string propertyName, } } - private void ValidateNull(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateNull(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { if (type.HasFlag(JsonObjectType.Null) && token != null && token.Type != JTokenType.Null) { @@ -186,7 +186,7 @@ private void ValidateNull(JToken token, JsonSchema4 schema, JsonObjectType type, } } - private void ValidateEnum(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateEnum(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.Enumeration.Contains(null) && token?.Type == JTokenType.Null) return; @@ -195,7 +195,7 @@ private void ValidateEnum(JToken token, JsonSchema4 schema, string propertyName, errors.Add(new ValidationError(ValidationErrorKind.NotInEnumeration, propertyName, propertyPath, token, schema)); } - private void ValidateString(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateString(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { var isString = token.Type == JTokenType.String || token.Type == JTokenType.Date || token.Type == JTokenType.Guid || token.Type == JTokenType.TimeSpan || @@ -238,7 +238,7 @@ private void ValidateString(JToken token, JsonSchema4 schema, JsonObjectType typ } } - private void ValidateNumber(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateNumber(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { if (type.HasFlag(JsonObjectType.Number) && token.Type != JTokenType.Float && token.Type != JTokenType.Integer) { @@ -288,7 +288,7 @@ private void ValidateNumber(JToken token, JsonSchema4 schema, JsonObjectType typ } } - private void ValidateInteger(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateInteger(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { if (type.HasFlag(JsonObjectType.Integer) && token.Type != JTokenType.Integer) { @@ -296,7 +296,7 @@ private void ValidateInteger(JToken token, JsonSchema4 schema, JsonObjectType ty } } - private void ValidateBoolean(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateBoolean(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { if (type.HasFlag(JsonObjectType.Boolean) && token.Type != JTokenType.Boolean) { @@ -304,7 +304,7 @@ private void ValidateBoolean(JToken token, JsonSchema4 schema, JsonObjectType ty } } - private void ValidateObject(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateObject(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { if (type.HasFlag(JsonObjectType.Object) && !(token is JObject)) { @@ -312,7 +312,7 @@ private void ValidateObject(JToken token, JsonSchema4 schema, JsonObjectType typ } } - private void ValidateProperties(JToken token, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateProperties(JToken token, JsonSchema schema, string propertyName, string propertyPath, List errors) { var obj = token as JObject; if (obj == null && schema.Type.HasFlag(JsonObjectType.Null)) @@ -365,19 +365,19 @@ private string GetPropertyPath(string propertyPath, string propertyName) return !string.IsNullOrEmpty(propertyPath) ? propertyPath + "." + propertyName : propertyName; } - private void ValidateMaxProperties(JToken token, IList properties, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateMaxProperties(JToken token, IList properties, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.MaxProperties > 0 && properties.Count() > schema.MaxProperties) errors.Add(new ValidationError(ValidationErrorKind.TooManyProperties, propertyName, propertyPath, token, schema)); } - private void ValidateMinProperties(JToken token, IList properties, JsonSchema4 schema, string propertyName, string propertyPath, List errors) + private void ValidateMinProperties(JToken token, IList properties, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.MinProperties > 0 && properties.Count() < schema.MinProperties) errors.Add(new ValidationError(ValidationErrorKind.TooFewProperties, propertyName, propertyPath, token, schema)); } - private void ValidatePatternProperties(List additionalProperties, JsonSchema4 schema, List errors) + private void ValidatePatternProperties(List additionalProperties, JsonSchema schema, List errors) { foreach (var property in additionalProperties.ToArray()) { @@ -395,7 +395,7 @@ private void ValidatePatternProperties(List additionalProperties, Jso } } - private void ValidateAdditionalProperties(JToken token, List additionalProperties, JsonSchema4 schema, + private void ValidateAdditionalProperties(JToken token, List additionalProperties, JsonSchema schema, string propertyName, string propertyPath, List errors) { if (schema.AdditionalPropertiesSchema != null) @@ -418,7 +418,7 @@ private void ValidateAdditionalProperties(JToken token, List addition } } - private void ValidateArray(JToken token, JsonSchema4 schema, JsonObjectType type, string propertyName, string propertyPath, List errors) + private void ValidateArray(JToken token, JsonSchema schema, JsonObjectType type, string propertyName, string propertyPath, List errors) { if (token is JArray array) { @@ -452,7 +452,7 @@ private void ValidateArray(JToken token, JsonSchema4 schema, JsonObjectType type errors.Add(new ValidationError(ValidationErrorKind.ArrayExpected, propertyName, propertyPath, token, schema)); } - private void ValidateAdditionalItems(JToken item, JsonSchema4 schema, int index, string propertyPath, List errors) + private void ValidateAdditionalItems(JToken item, JsonSchema schema, int index, string propertyPath, List errors) { if (schema.Items.Count > 0) { @@ -479,13 +479,13 @@ private void ValidateAdditionalItems(JToken item, JsonSchema4 schema, int index, } } - private ChildSchemaValidationError TryCreateChildSchemaError(JToken token, JsonSchema4 schema, ValidationErrorKind errorKind, string property, string path) + private ChildSchemaValidationError TryCreateChildSchemaError(JToken token, JsonSchema schema, ValidationErrorKind errorKind, string property, string path) { var errors = Validate(token, schema.ActualSchema, null, path); if (errors.Count == 0) return null; - var errorDictionary = new Dictionary>(); + var errorDictionary = new Dictionary>(); errorDictionary.Add(schema, errors); return new ChildSchemaValidationError(errorKind, property, path, errorDictionary, token, schema); diff --git a/src/NJsonSchema/Validation/MultiTypeValidationError.cs b/src/NJsonSchema/Validation/MultiTypeValidationError.cs index c837cf8c3..a7bd02ae3 100644 --- a/src/NJsonSchema/Validation/MultiTypeValidationError.cs +++ b/src/NJsonSchema/Validation/MultiTypeValidationError.cs @@ -22,9 +22,9 @@ public class MultiTypeValidationError : ValidationError /// The token that failed to validate. /// The schema that contains the validation rule. #if !LEGACY - public MultiTypeValidationError(ValidationErrorKind kind, string property, string path, IReadOnlyDictionary> errors, JToken token, JsonSchema4 schema) + public MultiTypeValidationError(ValidationErrorKind kind, string property, string path, IReadOnlyDictionary> errors, JToken token, JsonSchema schema) #else - public MultiTypeValidationError(ValidationErrorKind kind, string property, string path, IDictionary> errors, JToken token, JsonSchema4 schema) + public MultiTypeValidationError(ValidationErrorKind kind, string property, string path, IDictionary> errors, JToken token, JsonSchema schema) #endif : base(kind, property, path, token, schema) { diff --git a/src/NJsonSchema/Validation/ValidationError.cs b/src/NJsonSchema/Validation/ValidationError.cs index 6ca94cddc..d04b1bac3 100644 --- a/src/NJsonSchema/Validation/ValidationError.cs +++ b/src/NJsonSchema/Validation/ValidationError.cs @@ -20,7 +20,7 @@ public class ValidationError /// The property path. /// The token that failed to validate. /// The schema that contains the validation rule. - public ValidationError(ValidationErrorKind errorKind, string propertyName, string propertyPath, JToken token, JsonSchema4 schema) + public ValidationError(ValidationErrorKind errorKind, string propertyName, string propertyPath, JToken token, JsonSchema schema) { Kind = errorKind; Property = propertyName; @@ -61,7 +61,7 @@ public ValidationError(ValidationErrorKind errorKind, string propertyName, strin public int LinePosition { get; private set; } /// Gets the schema element that contains the validation rule. - public JsonSchema4 Schema { get; private set; } + public JsonSchema Schema { get; private set; } /// Returns a string that represents the current object. /// A string that represents the current object. diff --git a/src/NJsonSchema/Visitors/JsonReferenceVisitorBase.cs b/src/NJsonSchema/Visitors/JsonReferenceVisitorBase.cs index 644385b31..e60edc020 100644 --- a/src/NJsonSchema/Visitors/JsonReferenceVisitorBase.cs +++ b/src/NJsonSchema/Visitors/JsonReferenceVisitorBase.cs @@ -18,7 +18,7 @@ namespace NJsonSchema.Visitors { - /// Visitor to transform an object with objects. + /// Visitor to transform an object with objects. public abstract class JsonReferenceVisitorBase { private readonly IContractResolver _contractResolver; @@ -74,59 +74,59 @@ protected virtual async Task VisitAsync(object obj, string path, string typeName } } - if (obj is JsonSchema4 schema) + if (obj is JsonSchema schema) { if (schema.Reference != null) - await VisitAsync(schema.Reference, path, null, checkedObjects, o => schema.Reference = (JsonSchema4)o).ConfigureAwait(false); + await VisitAsync(schema.Reference, path, null, checkedObjects, o => schema.Reference = (JsonSchema)o).ConfigureAwait(false); if (schema.AdditionalItemsSchema != null) - await VisitAsync(schema.AdditionalItemsSchema, path + "/additionalItems", null, checkedObjects, o => schema.AdditionalItemsSchema = (JsonSchema4)o).ConfigureAwait(false); + await VisitAsync(schema.AdditionalItemsSchema, path + "/additionalItems", null, checkedObjects, o => schema.AdditionalItemsSchema = (JsonSchema)o).ConfigureAwait(false); if (schema.AdditionalPropertiesSchema != null) - await VisitAsync(schema.AdditionalPropertiesSchema, path + "/additionalProperties", null, checkedObjects, o => schema.AdditionalPropertiesSchema = (JsonSchema4)o).ConfigureAwait(false); + await VisitAsync(schema.AdditionalPropertiesSchema, path + "/additionalProperties", null, checkedObjects, o => schema.AdditionalPropertiesSchema = (JsonSchema)o).ConfigureAwait(false); if (schema.Item != null) - await VisitAsync(schema.Item, path + "/items", null, checkedObjects, o => schema.Item = (JsonSchema4)o).ConfigureAwait(false); + await VisitAsync(schema.Item, path + "/items", null, checkedObjects, o => schema.Item = (JsonSchema)o).ConfigureAwait(false); for (var i = 0; i < schema.Items.Count; i++) { var index = i; - await VisitAsync(schema.Items.ElementAt(i), path + "/items[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.Items, index, (JsonSchema4)o)).ConfigureAwait(false); + await VisitAsync(schema.Items.ElementAt(i), path + "/items[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.Items, index, (JsonSchema)o)).ConfigureAwait(false); } for (var i = 0; i < schema.AllOf.Count; i++) { var index = i; - await VisitAsync(schema.AllOf.ElementAt(i), path + "/allOf[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.AllOf, index, (JsonSchema4)o)).ConfigureAwait(false); + await VisitAsync(schema.AllOf.ElementAt(i), path + "/allOf[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.AllOf, index, (JsonSchema)o)).ConfigureAwait(false); } for (var i = 0; i < schema.AnyOf.Count; i++) { var index = i; - await VisitAsync(schema.AnyOf.ElementAt(i), path + "/anyOf[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.AnyOf, index, (JsonSchema4)o)).ConfigureAwait(false); + await VisitAsync(schema.AnyOf.ElementAt(i), path + "/anyOf[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.AnyOf, index, (JsonSchema)o)).ConfigureAwait(false); } for (var i = 0; i < schema.OneOf.Count; i++) { var index = i; - await VisitAsync(schema.OneOf.ElementAt(i), path + "/oneOf[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.OneOf, index, (JsonSchema4)o)).ConfigureAwait(false); + await VisitAsync(schema.OneOf.ElementAt(i), path + "/oneOf[" + i + "]", null, checkedObjects, o => ReplaceOrDelete(schema.OneOf, index, (JsonSchema)o)).ConfigureAwait(false); } if (schema.Not != null) - await VisitAsync(schema.Not, path + "/not", null, checkedObjects, o => schema.Not = (JsonSchema4)o).ConfigureAwait(false); + await VisitAsync(schema.Not, path + "/not", null, checkedObjects, o => schema.Not = (JsonSchema)o).ConfigureAwait(false); foreach (var p in schema.Properties.ToArray()) - await VisitAsync(p.Value, path + "/properties/" + p.Key, p.Key, checkedObjects, o => schema.Properties[p.Key] = (JsonProperty)o).ConfigureAwait(false); + await VisitAsync(p.Value, path + "/properties/" + p.Key, p.Key, checkedObjects, o => schema.Properties[p.Key] = (JsonSchemaProperty)o).ConfigureAwait(false); foreach (var p in schema.PatternProperties.ToArray()) - await VisitAsync(p.Value, path + "/patternProperties/" + p.Key, null, checkedObjects, o => schema.PatternProperties[p.Key] = (JsonProperty)o).ConfigureAwait(false); + await VisitAsync(p.Value, path + "/patternProperties/" + p.Key, null, checkedObjects, o => schema.PatternProperties[p.Key] = (JsonSchemaProperty)o).ConfigureAwait(false); foreach (var p in schema.Definitions.ToArray()) { await VisitAsync(p.Value, path + "/definitions/" + p.Key, p.Key, checkedObjects, o => { if (o != null) - schema.Definitions[p.Key] = (JsonSchema4)o; + schema.Definitions[p.Key] = (JsonSchema)o; else schema.Definitions.Remove(p.Key); }).ConfigureAwait(false); @@ -156,7 +156,7 @@ await VisitAsync(dictionary[key], path + "/" + key, key.ToString(), checkedObjec { if (o != null) { - dictionary[key] = (JsonSchema4)o; + dictionary[key] = (JsonSchema)o; } else { diff --git a/src/NJsonSchema/Visitors/JsonSchemaVisitorBase.cs b/src/NJsonSchema/Visitors/JsonSchemaVisitorBase.cs index 6262a1180..4bd51cef6 100644 --- a/src/NJsonSchema/Visitors/JsonSchemaVisitorBase.cs +++ b/src/NJsonSchema/Visitors/JsonSchemaVisitorBase.cs @@ -11,15 +11,15 @@ namespace NJsonSchema.Visitors { - /// Visitor to transform an object with objects. + /// Visitor to transform an object with objects. public abstract class JsonSchemaVisitorBase : JsonReferenceVisitorBase { - /// Called when a is visited. + /// Called when a is visited. /// The visited schema. /// The path. /// The type name hint. /// The task. - protected abstract Task VisitSchemaAsync(JsonSchema4 schema, string path, string typeNameHint); + protected abstract Task VisitSchemaAsync(JsonSchema schema, string path, string typeNameHint); /// Called when a is visited. /// The visited schema. @@ -28,7 +28,7 @@ public abstract class JsonSchemaVisitorBase : JsonReferenceVisitorBase /// The task. protected override async Task VisitJsonReferenceAsync(IJsonReference reference, string path, string typeNameHint) { - if (reference is JsonSchema4 schema) + if (reference is JsonSchema schema) return await VisitSchemaAsync(schema, path, typeNameHint).ConfigureAwait(false); return reference;