diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index f062ef79d..16c4e934e 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -5,7 +5,7 @@
#
# - To turn off auto-generation set:
#
-# [GitHubActions (AutoGenerate = false)]
+# [CustomGitHubActions (AutoGenerate = false)]
#
# - To trigger manual generation invoke:
#
@@ -33,6 +33,10 @@ jobs:
name: windows-latest
runs-on: windows-latest
steps:
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 9.0
- uses: actions/checkout@v4
- name: 'Cache: .nuke/temp, ~/.nuget/packages'
uses: actions/cache@v4
@@ -48,6 +52,7 @@ jobs:
MYGET_API_KEY: ${{ secrets.MYGET_API_KEY }}
- name: 'Publish: artifacts'
uses: actions/upload-artifact@v4
+ if: runner.os == 'Windows'
with:
name: artifacts
path: artifacts
@@ -55,6 +60,10 @@ jobs:
name: ubuntu-latest
runs-on: ubuntu-latest
steps:
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 9.0
- uses: actions/checkout@v4
- name: 'Cache: .nuke/temp, ~/.nuget/packages'
uses: actions/cache@v4
@@ -70,6 +79,7 @@ jobs:
MYGET_API_KEY: ${{ secrets.MYGET_API_KEY }}
- name: 'Publish: artifacts'
uses: actions/upload-artifact@v4
+ if: runner.os == 'Windows'
with:
name: artifacts
path: artifacts
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 8e993f88d..41f2b2ff2 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -5,7 +5,7 @@
#
# - To turn off auto-generation set:
#
-# [GitHubActions (AutoGenerate = false)]
+# [CustomGitHubActions (AutoGenerate = false)]
#
# - To trigger manual generation invoke:
#
@@ -34,6 +34,10 @@ jobs:
name: windows-latest
runs-on: windows-latest
steps:
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 9.0
- uses: actions/checkout@v4
- name: 'Cache: .nuke/temp, ~/.nuget/packages'
uses: actions/cache@v4
@@ -48,6 +52,10 @@ jobs:
name: ubuntu-latest
runs-on: ubuntu-latest
steps:
+ - uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: |
+ 9.0
- uses: actions/checkout@v4
- name: 'Cache: .nuke/temp, ~/.nuget/packages'
uses: actions/cache@v4
diff --git a/Directory.Build.props b/Directory.Build.props
index ccc140a26..5c13ae385 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -33,12 +33,40 @@
latest-Recommended
true
- $(NoWarn);CA1200;CA1510;CA1716;CA1720
+ $(NoWarn);IDE0005;IDE0008;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0057;IDE0059;IDE0060;IDE0074;IDE0078;IDE0083;IDE0090;IDE0100;IDE0130;IDE0160;IDE0260;IDE0290;IDE1005;CA1200;CA1510;CA1716;CA1720;CA2263
diff --git a/build/Build.CI.GitHubActions.cs b/build/Build.CI.GitHubActions.cs
index 8591806a3..3daec2eef 100644
--- a/build/Build.CI.GitHubActions.cs
+++ b/build/Build.CI.GitHubActions.cs
@@ -1,6 +1,10 @@
+using System.Collections.Generic;
using Nuke.Common.CI.GitHubActions;
+using Nuke.Common.CI.GitHubActions.Configuration;
+using Nuke.Common.Execution;
+using Nuke.Common.Utilities;
-[GitHubActions(
+[CustomGitHubActions(
"pr",
GitHubActionsImage.WindowsLatest,
GitHubActionsImage.UbuntuLatest,
@@ -12,7 +16,7 @@
CacheKeyFiles = ["global.json", "src/**/*.csproj", "src/**/package.json"],
ConcurrencyCancelInProgress = true)
]
-[GitHubActions(
+[CustomGitHubActions(
"build",
GitHubActionsImage.WindowsLatest,
GitHubActionsImage.UbuntuLatest,
@@ -21,8 +25,60 @@
OnPushIncludePaths = ["**/*.*"],
OnPushExcludePaths = ["**/*.md"],
PublishArtifacts = true,
+ PublishCondition = "runner.os == 'Windows'",
InvokedTargets = [nameof(Compile), nameof(Test), nameof(Pack), nameof(Publish)],
ImportSecrets = ["NUGET_API_KEY", "MYGET_API_KEY"],
CacheKeyFiles = ["global.json", "src/**/*.csproj", "src/**/package.json"])
]
public partial class Build;
+
+class CustomGitHubActionsAttribute : GitHubActionsAttribute
+{
+ public CustomGitHubActionsAttribute(string name, GitHubActionsImage image, params GitHubActionsImage[] images) : base(name, image, images)
+ {
+ }
+
+ protected override GitHubActionsJob GetJobs(GitHubActionsImage image, IReadOnlyCollection relevantTargets)
+ {
+ var job = base.GetJobs(image, relevantTargets);
+
+ var newSteps = new List(job.Steps);
+
+ // only need to list the ones that are missing from default image
+ newSteps.Insert(0, new GitHubActionsSetupDotNetStep(["9.0"]));
+
+ job.Steps = newSteps.ToArray();
+ return job;
+ }
+}
+
+class GitHubActionsSetupDotNetStep : GitHubActionsStep
+{
+ public GitHubActionsSetupDotNetStep(string[] versions)
+ {
+ Versions = versions;
+ }
+
+ string[] Versions { get; }
+
+ public override void Write(CustomFileWriter writer)
+ {
+ writer.WriteLine("- uses: actions/setup-dotnet@v4");
+
+ using (writer.Indent())
+ {
+ writer.WriteLine("with:");
+ using (writer.Indent())
+ {
+ writer.WriteLine("dotnet-version: |");
+ using (writer.Indent())
+ {
+ foreach (var version in Versions)
+ {
+ writer.WriteLine(version);
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/build/_build.csproj b/build/_build.csproj
index d8b48b5fd..48b0b7dfe 100644
--- a/build/_build.csproj
+++ b/build/_build.csproj
@@ -22,6 +22,7 @@
+
diff --git a/global.json b/global.json
index 989a69caf..f15a95928 100644
--- a/global.json
+++ b/global.json
@@ -1,6 +1,6 @@
{
"sdk": {
- "version": "8.0.100",
+ "version": "9.0.100",
"rollForward": "latestMinor"
}
}
\ No newline at end of file
diff --git a/src/NJsonSchema.Benchmark/Program.cs b/src/NJsonSchema.Benchmark/Program.cs
index 2bf2ba8aa..1dd3a424d 100644
--- a/src/NJsonSchema.Benchmark/Program.cs
+++ b/src/NJsonSchema.Benchmark/Program.cs
@@ -10,7 +10,9 @@ public static void Main(string[] args)
BenchmarkDotNet.Running.BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).RunAllJoined();
}
+#pragma warning disable IDE0051
private static void RunCsharpBenchmark()
+#pragma warning restore IDE0051
{
var benchmark = new CsharpGeneratorBenchmark();
benchmark.Setup().GetAwaiter().GetResult();
diff --git a/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs b/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs
index b9ab6021d..2006f8e90 100644
--- a/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs
+++ b/src/NJsonSchema.Benchmark/SchemaGenerationBenchmarks.cs
@@ -61,7 +61,7 @@ public class WritingInstrument
{
public static Type[] GetKnownTypes()
{
- return new[] { typeof(Pen), typeof(Pencil) };
+ return [typeof(Pen), typeof(Pencil)];
}
public string Baz { get; set; }
diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs
index 4301c355d..4244eec55 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/CSharpJsonSerializerGeneratorTests.cs
@@ -30,7 +30,7 @@ public void When_using_NewtonsoftJson_with_JsonConverters_GenerateJsonSerializer
var settings = new CSharpGeneratorSettings
{
JsonLibrary = CSharpJsonLibrary.NewtonsoftJson,
- JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" }
+ JsonConverters = ["CustomConverter1", "CustomConverter2"]
};
//// Act
@@ -68,7 +68,7 @@ public void When_using_NewtonsoftJson_with_HandleReferences_and_JsonConverters_a
{
JsonLibrary = CSharpJsonLibrary.NewtonsoftJson,
HandleReferences = true,
- JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" },
+ JsonConverters = ["CustomConverter1", "CustomConverter2"],
JsonSerializerSettingsTransformationMethod = "TestJsonSerializerSettingsTransformationMethod",
};
@@ -88,7 +88,7 @@ public void When_using_SystemTextJson_with_JsonConverters_GenerateJsonConverters
var settings = new CSharpGeneratorSettings
{
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
- JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" }
+ JsonConverters = ["CustomConverter1", "CustomConverter2"]
};
//// Act
@@ -107,7 +107,7 @@ public void When_using_NewtonsoftJson_with_JsonConverters_GenerateJsonConverters
var settings = new CSharpGeneratorSettings
{
JsonLibrary = CSharpJsonLibrary.NewtonsoftJson,
- JsonConverters = new string[] { "CustomConverter1", "CustomConverter2" }
+ JsonConverters = ["CustomConverter1", "CustomConverter2"]
};
//// Act
diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs
index d1eb0b828..129d132bc 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/DefaultPropertyTests.cs
@@ -91,8 +91,10 @@ public async Task When_generating_CSharp_code_then_default_value_generates_expec
}");
//// Act
- var settings = new CSharpGeneratorSettings();
- settings.GenerateDefaultValues = true;
+ var settings = new CSharpGeneratorSettings
+ {
+ GenerateDefaultValues = true
+ };
var generator = new CSharpGenerator(document, settings);
var code = generator.GenerateFile();
@@ -117,8 +119,10 @@ public async Task When_generating_CSharp_code_then_default_value_with_decimal_ge
}");
//// Act
- var settings = new CSharpGeneratorSettings();
- settings.GenerateDefaultValues = true;
+ var settings = new CSharpGeneratorSettings
+ {
+ GenerateDefaultValues = true
+ };
var generator = new CSharpGenerator(document, settings);
var code = generator.GenerateFile();
@@ -149,8 +153,10 @@ public async Task When_generating_CSharp_code_then_default_value_of_dictionary_w
}");
// Act
- var settings = new CSharpGeneratorSettings();
- settings.GenerateDefaultValues = true;
+ var settings = new CSharpGeneratorSettings
+ {
+ GenerateDefaultValues = true
+ };
var generator = new CSharpGenerator(document, settings);
var code = generator.GenerateFile();
@@ -181,8 +187,10 @@ public async Task When_generating_CSharp_code_then_default_value_of_array_of_arr
}");
// Act
- var settings = new CSharpGeneratorSettings();
- settings.GenerateDefaultValues = true;
+ var settings = new CSharpGeneratorSettings
+ {
+ GenerateDefaultValues = true
+ };
var generator = new CSharpGenerator(document, settings);
var code = generator.GenerateFile();
diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs
index cd5fb9798..8bac3428a 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/GeneralGeneratorTests.cs
@@ -66,14 +66,15 @@ public async Task When_code_is_generated_then_toolchain_version_is_printed()
AssertCompile(output);
}
- class CustomPropertyNameGenerator : IPropertyNameGenerator
+ private class CustomPropertyNameGenerator : IPropertyNameGenerator
{
public string Generate(JsonSchemaProperty property)
{
return "MyCustom" + ConversionUtilities.ConvertToUpperCamelCase(property.Name, true);
}
}
- class CustomTypeNameGenerator : ITypeNameGenerator
+
+ private class CustomTypeNameGenerator : ITypeNameGenerator
{
public string Generate(JsonSchema schema, string typeNameHint, IEnumerable reservedTypeNames)
{
@@ -134,10 +135,12 @@ public async Task When_property_name_is_created_by_custom_fun_then_attribute_is_
//// Arrange
var schema = NewtonsoftJsonSchemaGenerator.FromType();
var schemaData = schema.ToJson();
- var settings = new CSharpGeneratorSettings();
+ var settings = new CSharpGeneratorSettings
+ {
+ TypeNameGenerator = new CustomTypeNameGenerator(),
+ PropertyNameGenerator = new CustomPropertyNameGenerator()
+ };
- settings.TypeNameGenerator = new CustomTypeNameGenerator();
- settings.PropertyNameGenerator = new CustomPropertyNameGenerator();
var generator = new CSharpGenerator(schema, settings);
//// Act
@@ -454,8 +457,10 @@ private static async Task CreateGeneratorAsync()
{
var schema = NewtonsoftJsonSchemaGenerator.FromType();
var schemaData = schema.ToJson();
- var settings = new CSharpGeneratorSettings();
- settings.Namespace = "MyNamespace";
+ var settings = new CSharpGeneratorSettings
+ {
+ Namespace = "MyNamespace"
+ };
var generator = new CSharpGenerator(schema, settings);
return generator;
}
@@ -664,11 +669,16 @@ 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 JsonSchema();
- schema.Type = JsonObjectType.Object;
- schema.Properties["foo"] = new JsonSchemaProperty
+ var schema = new JsonSchema
{
- Type = JsonObjectType.Number
+ Type = JsonObjectType.Object,
+ Properties =
+ {
+ ["foo"] = new JsonSchemaProperty
+ {
+ Type = JsonObjectType.Number
+ }
+ }
};
//// Act
@@ -2006,7 +2016,7 @@ public static Person FromJson(string data)
var generator = await CreateGeneratorAsync();
generator.Settings.JsonLibrary = CSharpJsonLibrary.SystemTextJson;
generator.Settings.GenerateJsonMethods = true;
- generator.Settings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" };
+ generator.Settings.JsonConverters = ["CustomConverter1", "CustomConverter2"];
//// Act
var output = generator.GenerateFile("MyClass");
@@ -2083,7 +2093,7 @@ public static Person FromJson(string data)
var generator = await CreateGeneratorAsync();
generator.Settings.JsonLibrary = CSharpJsonLibrary.NewtonsoftJson;
generator.Settings.GenerateJsonMethods = true;
- generator.Settings.JsonConverters = new[] { "CustomConverter1", "CustomConverter2" };
+ generator.Settings.JsonConverters = ["CustomConverter1", "CustomConverter2"];
//// Act
var output = generator.GenerateFile("MyClass");
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
index de2fd2574..0174b18e7 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
@@ -144,7 +144,7 @@ private static void RenamePropertyWithSameNameAsClass(string typeName, IEnumerab
number++;
}
- propertyWithSameNameAsClass.PropertyName = propertyWithSameNameAsClass.PropertyName + number;
+ propertyWithSameNameAsClass.PropertyName += number;
}
}
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs
index 3f8e30e6d..67c265f3c 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGeneratorSettings.cs
@@ -50,10 +50,9 @@ public CSharpGeneratorSettings()
ValueGenerator = new CSharpValueGenerator(this);
PropertyNameGenerator = new CSharpPropertyNameGenerator();
- TemplateFactory = new DefaultTemplateFactory(this, new Assembly[]
- {
+ TemplateFactory = new DefaultTemplateFactory(this, [
typeof(CSharpGeneratorSettings).GetTypeInfo().Assembly
- });
+ ]);
InlineNamedArrays = false;
InlineNamedDictionaries = false;
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs
index 815d8dd68..a3c3baa6e 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs
@@ -40,7 +40,7 @@ public static string GenerateJsonConvertersArrayCode(CSharpGeneratorSettings set
private static List GetJsonConverters(CSharpGeneratorSettings settings, IEnumerable? additionalJsonConverters)
{
- return (settings.JsonConverters ?? Array.Empty()).Concat(additionalJsonConverters ?? Array.Empty()).ToList();
+ return [.. settings.JsonConverters ?? [], .. additionalJsonConverters ?? []];
}
private static string GenerateForJsonLibrary(CSharpGeneratorSettings settings, List jsonConverters, bool hasJsonConverters)
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs
index 2a42c6df8..0496cfed9 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs
@@ -11,8 +11,9 @@ namespace NJsonSchema.CodeGeneration.CSharp
/// Generates the property name for a given CSharp .
public sealed class CSharpPropertyNameGenerator : IPropertyNameGenerator
{
- private static readonly char[] _reservedFirstPassChars = { '"', '\'', '@', '?', '!', '$', '[', ']', '(', ')', '.', '=', '+', '|' };
- private static readonly char[] _reservedSecondPassChars = { '*', ':', '-', '#', '&' };
+ private static readonly char[] _reservedFirstPassChars = ['"', '\'', '@', '?', '!', '$', '[', ']', '(', ')', '.', '=', '+', '|'
+ ];
+ private static readonly char[] _reservedSecondPassChars = ['*', ':', '-', '#', '&'];
/// Generates the property name.
/// The property.
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
index 5f329158e..4d7f369da 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
@@ -268,7 +268,9 @@ private string ResolveNumber(JsonSchema schema, bool isNullable)
};
if (string.IsNullOrWhiteSpace(numberType))
+ {
numberType = "double";
+ }
return isNullable ? numberType + "?" : numberType;
}
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
index 07356edf9..04fb5a1b2 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
@@ -17,11 +17,11 @@ namespace NJsonSchema.CodeGeneration.CSharp
public class CSharpValueGenerator : ValueGeneratorBase
{
private readonly CSharpGeneratorSettings _settings;
- private readonly List _typesWithStringConstructor = new List()
- {
+ private readonly List _typesWithStringConstructor =
+ [
"System.Guid",
"System.Uri"
- };
+ ];
/// Initializes a new instance of the class.
/// The settings.
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs
index 0855e9936..83d6bd0b0 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs
@@ -168,7 +168,7 @@ private static bool TryGetInt64(object value, out long valueInt64)
}
else
{
- valueInt64 = default(long);
+ valueInt64 = default;
return false;
}
}
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj b/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj
index 468231bfe..512925763 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj
+++ b/src/NJsonSchema.CodeGeneration.CSharp/NJsonSchema.CodeGeneration.CSharp.csproj
@@ -2,7 +2,6 @@
netstandard2.0;net462
- bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
diff --git a/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs
index fafb47efa..4a219de1e 100644
--- a/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs
+++ b/src/NJsonSchema.CodeGeneration.Tests/EnumGenerationTests.cs
@@ -44,7 +44,7 @@ public async Task When_string_and_integer_enum_used_then_two_enums_are_generated
var code = generator.GenerateFile("MyClass");
//// Assert
- Assert.Equal(3, code.Split(new[] { "export enum " }, StringSplitOptions.None).Count()); // two found
+ Assert.Equal(3, code.Split(["export enum "], StringSplitOptions.None).Count()); // two found
}
[Fact]
@@ -104,8 +104,9 @@ public async Task When_string_and_integer_enum_used_then_one_enum_is_generated_i
Assert.Contains("public enum Bar2\n", code);
Assert.Contains(" B = 5,", code); // B must be 5 even if B = 1 is first defined
- Assert.Equal(3, code.Split(new[] { "public enum " }, StringSplitOptions.None).Count()); // two found (one string and one integer based enum)
- Assert.Equal(3, code.Split(new[] { "[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]" }, StringSplitOptions.None).Count()); // two found
+ Assert.Equal(3, code.Split(["public enum "], StringSplitOptions.None).Count()); // two found (one string and one integer based enum)
+ Assert.Equal(3, code.Split(
+ ["[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]"], StringSplitOptions.None).Count()); // two found
}
[Fact]
diff --git a/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs b/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs
index f93750e43..56c0f6a31 100644
--- a/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs
+++ b/src/NJsonSchema.CodeGeneration.Tests/InheritanceSerializationTests.cs
@@ -55,7 +55,7 @@ public class SubClass2 : SubClass
public static Type[] GetTypes()
{
- return new Type[] { typeof(SubClass3) };
+ return [typeof(SubClass3)];
}
}
@@ -88,11 +88,11 @@ public async Task When_JsonInheritanceConverter_is_used_then_inheritance_is_corr
{
Foo = "foo",
Bar = "bar",
- SubElements = new List
- {
+ SubElements =
+ [
new SubClass1 { Prop1 = "x" },
- new SubClass3 { Prop2 = "x", Prop3 = "y"}
- }
+ new SubClass3 { Prop2 = "x", Prop3 = "y" }
+ ]
}
};
@@ -120,11 +120,11 @@ public async Task When_serializer_setting_is_changed_then_converter_uses_correct
{
Foo = "foo",
Bar = "bar",
- SubElements = new List
- {
+ SubElements =
+ [
new SubClass1 { Prop1 = "x" },
- new SubClass3 { Prop2 = "x", Prop3 = "y"}
- }
+ new SubClass3 { Prop2 = "x", Prop3 = "y" }
+ ]
}
};
@@ -189,14 +189,11 @@ public async Task JsonInheritanceConverter_is_thread_safe()
var tasks = new List();
for (int i = 0; i < 100; i++)
{
- tasks.Add(Task.Run(async () =>
- {
- await When_JsonInheritanceConverter_is_used_then_inheritance_is_correctly_serialized_and_deserialized();
- }));
+ tasks.Add(Task.Run(When_JsonInheritanceConverter_is_used_then_inheritance_is_correctly_serialized_and_deserialized));
}
//// Act
- await Task.WhenAll(tasks.ToArray());
+ await Task.WhenAll([.. tasks]);
//// Assert
// No exceptions
@@ -300,12 +297,7 @@ public async Task Subtypes_are_serialized_with_correct_discriminator()
var code = generator.GenerateFile();
var assembly = Compile(code);
- var type = assembly.GetType("foo.Foo");
- if (type == null)
- {
- throw new Exception("Foo not found in " + String.Join(", ", assembly.GetTypes().Select(t => t.Name)));
- }
-
+ var type = assembly.GetType("foo.Foo") ?? throw new Exception("Foo not found in " + String.Join(", ", assembly.GetTypes().Select(t => t.Name)));
var bar = JsonConvert.DeserializeObject(@"{""discriminator"":""bar""}", type);
//// Assert
@@ -331,19 +323,17 @@ private Assembly Compile(string code)
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Linq.Expressions.dll"),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.Extensions.dll"));
- using (var stream = new MemoryStream())
- {
- var result = compilation.Emit(stream);
-
- if (!result.Success)
- {
- throw new Exception(String.Join(", ", result.Diagnostics
- .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error)
- .Select(d => d.Location.GetLineSpan().StartLinePosition + " - " + d.GetMessage())) + "\n" + code);
- }
+ using var stream = new MemoryStream();
+ var result = compilation.Emit(stream);
- return Assembly.Load(stream.GetBuffer());
+ if (!result.Success)
+ {
+ throw new Exception(String.Join(", ", result.Diagnostics
+ .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error)
+ .Select(d => d.Location.GetLineSpan().StartLinePosition + " - " + d.GetMessage())) + "\n" + code);
}
+
+ return Assembly.Load(stream.GetBuffer());
}
}
}
diff --git a/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs b/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs
index 37097d1ea..d341ef0e2 100644
--- a/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs
+++ b/src/NJsonSchema.CodeGeneration.Tests/LiquidTests.cs
@@ -75,11 +75,11 @@ public void CanGetFriendlyErrorSuggestingUsingElsif()
{
TemplateDirectory = "Templates"
};
- var templateFactory = new DefaultTemplateFactory(settings, Array.Empty());
+ var templateFactory = new DefaultTemplateFactory(settings, []);
var template1 = templateFactory.CreateTemplate("csharp", "elseif", new object());
// Act
- var ex = Assert.Throws(() => template1.Render());
+ var ex = Assert.Throws(template1.Render);
// Assert
Assert.Contains(", did you use 'elseif' instead of correct 'elsif'?", ex.Message);
diff --git a/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj b/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj
index cd1ef8ba1..a565cdf18 100644
--- a/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj
+++ b/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj
@@ -3,7 +3,7 @@
net8.0;net472
false
- $(NoWarn),1998,1591,618
+ $(NoWarn),1998,1591,618,IDE1006
disable
false
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs
index 31c7da35b..3543fa461 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/ExtensionCodeTests.cs
@@ -57,7 +57,7 @@ public void When_extension_code_is_processed_then_code_and_classes_are_correctly
var code = Code;
//// Act
- var extensionCode = new TypeScriptExtensionCode(code, new[] { "Foo", "Bar" }, new [] { "BaseClass" });
+ var extensionCode = new TypeScriptExtensionCode(code, ["Foo", "Bar"], ["BaseClass"]);
//// Assert
Assert.True(extensionCode.ExtensionClasses.ContainsKey("Foo"));
@@ -103,7 +103,7 @@ public async Task When_classes_have_extension_code_then_class_body_is_copied()
//// Act
var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings
{
- ExtendedClasses = new[] { "Foo", "Bar" },
+ ExtendedClasses = ["Foo", "Bar"],
ExtensionCode = Code
});
var code = generator.GenerateFile();
@@ -131,7 +131,7 @@ protected transformOptions(options: RequestInit): Promise {
}";
//// Act
- var extensionCode = new TypeScriptExtensionCode(code, Array.Empty(), new[] { "UseHttpCookiesForApi" });
+ var extensionCode = new TypeScriptExtensionCode(code, [], ["UseHttpCookiesForApi"]);
//// Assert
Assert.Empty(extensionCode.ExtensionClasses);
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs
index 7ca7f63bd..715a5557a 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/InheritanceTests.cs
@@ -360,7 +360,7 @@ export class ExceptionBase extends generated.ExceptionBase {
var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings
{
ExtensionCode = extensionCode,
- ExtendedClasses = new[] { "ExceptionBase" },
+ ExtendedClasses = ["ExceptionBase"],
});
//// Act
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj b/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj
index 5227ca505..5f20732fa 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/NJsonSchema.CodeGeneration.TypeScript.csproj
@@ -4,10 +4,6 @@
netstandard2.0;net462
-
- bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
-
-
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs
index f6f5c9a0b..5c476c94f 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs
@@ -53,8 +53,7 @@ public TypeScriptGenerator(object rootObject, TypeScriptGeneratorSettings settin
/// The code.
public override IEnumerable GenerateTypes()
{
- _extensionCode = _extensionCode ??
- new TypeScriptExtensionCode(Settings.ExtensionCode, Settings.ExtendedClasses);
+ _extensionCode ??= new TypeScriptExtensionCode(Settings.ExtensionCode, Settings.ExtendedClasses);
return GenerateTypes(_extensionCode);
}
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs
index c627f1788..753832235 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGeneratorSettings.cs
@@ -34,13 +34,12 @@ public TypeScriptGeneratorSettings()
ValueGenerator = new TypeScriptValueGenerator(this);
PropertyNameGenerator = new TypeScriptPropertyNameGenerator();
- TemplateFactory = new DefaultTemplateFactory(this, new Assembly[]
- {
+ TemplateFactory = new DefaultTemplateFactory(this, [
typeof(TypeScriptGeneratorSettings).GetTypeInfo().Assembly
- });
+ ]);
- ClassTypes = Array.Empty();
- ExtendedClasses = Array.Empty();
+ ClassTypes = [];
+ ExtendedClasses = [];
InlineNamedDictionaries = false;
GenerateTypeCheckFunctions = false;
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs
index 6f92c8e84..3ae5ff610 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptPropertyNameGenerator.cs
@@ -14,8 +14,8 @@ namespace NJsonSchema.CodeGeneration.TypeScript
/// Generates the property name for a given TypeScript .
public sealed class TypeScriptPropertyNameGenerator : IPropertyNameGenerator
{
- private static readonly char[] _reservedFirstPassChars = { '"', '@', '?', '.', '=', '+' };
- private static readonly char[] _reservedSecondPassChars = { '*', ':', '-' };
+ private static readonly char[] _reservedFirstPassChars = ['"', '@', '?', '.', '=', '+'];
+ private static readonly char[] _reservedSecondPassChars = ['*', ':', '-'];
/// Gets or sets the reserved names.
public HashSet ReservedPropertyNames { get; set; } = new(StringComparer.Ordinal) { "constructor", "init", "fromJS", "toJSON" };
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs
index b61f02fd2..d400ae8db 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs
@@ -310,7 +310,7 @@ private string ResolveArrayOrTuple(JsonSchema schema, string? typeNameHint, bool
if (Settings.UseLeafType)
{
var itemTypes = Resolve(schema.Item, true, typeNameHint) // TODO: Make typeNameHint singular if possible
- .Split(new[] { UnionPipe }, StringSplitOptions.RemoveEmptyEntries)
+ .Split([UnionPipe], StringSplitOptions.RemoveEmptyEntries)
.Select(x => GetNullableItemType(schema, prefix + x))
.ToList();
diff --git a/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs b/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
index e53f6f4e3..56519326c 100644
--- a/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
+++ b/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
@@ -31,7 +31,7 @@ public static IEnumerable OrderByBaseDependency(this IEnumerable(results);
// we need new list to iterate as we modify the original
- var resultIterator = results as List ?? newResults.ToList();
+ var resultIterator = results as List ?? [.. newResults];
foreach (var result in resultIterator)
{
if (!string.IsNullOrEmpty(GetActualBaseName(result.BaseTypeName)))
diff --git a/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs b/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs
index 1b08ecc9b..c89009fba 100644
--- a/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs
+++ b/src/NJsonSchema.CodeGeneration/CodeGeneratorSettingsBase.cs
@@ -20,7 +20,7 @@ public CodeGeneratorSettingsBase()
#pragma warning restore CS8618
{
GenerateDefaultValues = true;
- ExcludedTypeNames = Array.Empty();
+ ExcludedTypeNames = [];
}
/// Gets or sets the schema type (default: JsonSchema).
diff --git a/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs b/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
index 2f71e31be..75ee4db90 100644
--- a/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs
@@ -14,8 +14,7 @@ namespace NJsonSchema.CodeGeneration
/// The default enumeration name generator.
public class DefaultEnumNameGenerator : IEnumNameGenerator
{
- private readonly static Regex _invalidNameCharactersPattern = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]");
- private const string _defaultReplacementCharacter = "_";
+ private static readonly Regex _invalidNameCharactersPattern = new Regex(@"[^\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]");
/// Generates the enumeration name/key of the given enumeration entry.
/// The index of the enumeration value (check and ).
diff --git a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs
index 9ded5c121..6206b7ce9 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)
return new LiquidTemplate(
language,
template,
- (lang, name) => GetLiquidTemplate(lang, name),
+ GetLiquidTemplate,
model,
GetToolchainVersion(),
_settings);
@@ -91,10 +91,8 @@ protected virtual string GetEmbeddedLiquidTemplate(string language, string templ
var resource = assembly.GetManifestResourceStream(resourceName);
if (resource != null)
{
- using (var reader = new StreamReader(resource))
- {
- return reader.ReadToEnd();
- }
+ using var reader = new StreamReader(resource);
+ return reader.ReadToEnd();
}
throw new InvalidOperationException("Could not load template '" + template + "' for language '" + language + "'.");
diff --git a/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs b/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs
index c8d370aeb..a3048079b 100644
--- a/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs
+++ b/src/NJsonSchema.CodeGeneration/TypeResolverBase.cs
@@ -16,7 +16,7 @@ public abstract class TypeResolverBase
{
private readonly CodeGeneratorSettingsBase _settings;
internal readonly Dictionary _generatedTypeNames = new();
- private readonly HashSet _reservedTypeNames = new();
+ private readonly HashSet _reservedTypeNames = [];
/// Initializes a new instance of the class.
/// The settings.
diff --git a/src/NJsonSchema.Demo.Performance/Program.cs b/src/NJsonSchema.Demo.Performance/Program.cs
index 1a83f85c8..65ccdf31a 100644
--- a/src/NJsonSchema.Demo.Performance/Program.cs
+++ b/src/NJsonSchema.Demo.Performance/Program.cs
@@ -62,7 +62,7 @@ public class WritingInstrument
{
public static Type[] GetKnownTypes()
{
- return new[] { typeof(Pen), typeof(Pencil) };
+ return [typeof(Pen), typeof(Pencil)];
}
public string Baz { get; set; }
diff --git a/src/NJsonSchema.Demo/Program.cs b/src/NJsonSchema.Demo/Program.cs
index 800f745cf..a5593010d 100644
--- a/src/NJsonSchema.Demo/Program.cs
+++ b/src/NJsonSchema.Demo/Program.cs
@@ -10,7 +10,7 @@ namespace NJsonSchema.Demo
{
public class Program
{
- static void Main(string[] args)
+ private static void Main(string[] args)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
diff --git a/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs b/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs
index e68a8a3ea..edc0e6bc9 100644
--- a/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs
+++ b/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs
@@ -106,14 +106,13 @@ public override bool CanConvert(Type objectType)
return null;
}
- var newSerializer = new JsonSerializer();
- newSerializer.ContractResolver = (IContractResolver)Activator.CreateInstance(serializer.ContractResolver.GetType());
+ var newSerializer = new JsonSerializer
+ {
+ ContractResolver = (IContractResolver)Activator.CreateInstance(serializer.ContractResolver.GetType())
+ };
var field = JsonExceptionConverter.GetField(typeof(DefaultContractResolver), "_sharedCache");
- if (field != null)
- {
- field.SetValue(newSerializer.ContractResolver, false);
- }
+ field?.SetValue(newSerializer.ContractResolver, false);
dynamic resolver = newSerializer.ContractResolver;
if (newSerializer.ContractResolver.GetType().GetRuntimeProperty("IgnoreSerializableAttribute") != null)
@@ -126,8 +125,7 @@ public override bool CanConvert(Type objectType)
resolver.IgnoreSerializableInterface = true;
}
- JToken? token;
- if (jObject.TryGetValue("discriminator", StringComparison.OrdinalIgnoreCase, out token))
+ if (jObject.TryGetValue("discriminator", StringComparison.OrdinalIgnoreCase, out JToken? token))
{
var discriminator = token.Value();
if (objectType.Name.Equals(discriminator, StringComparison.Ordinal) == false)
@@ -175,10 +173,7 @@ public override bool CanConvert(Type objectType)
else
{
field = JsonExceptionConverter.GetField(objectType, "_" + fieldNameSuffix);
- if (field != null)
- {
- field.SetValue(value, propertyValue);
- }
+ field?.SetValue(value, propertyValue);
}
}
}
@@ -205,10 +200,8 @@ public override bool CanConvert(Type objectType)
}
- private static readonly HashSet ignoredExceptionProperties = new()
- {
- "Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult"
- };
+ private static readonly HashSet ignoredExceptionProperties =
+ ["Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult"];
private static Dictionary GetExceptionProperties(Type exceptionType)
{
diff --git a/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs b/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs
index aff50579c..dd9bbe644 100644
--- a/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs
+++ b/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs
@@ -268,7 +268,7 @@ protected virtual Type GetDiscriminatorType(JObject jObject, Type objectType, st
var method = type.GetRuntimeMethod((string)attribute.MethodName, Type.EmptyTypes);
if (method != null)
{
- var types = (System.Collections.Generic.IEnumerable)method.Invoke(null, Array.Empty
-
+
diff --git a/src/NJsonSchema/OpenApiDiscriminator.cs b/src/NJsonSchema/OpenApiDiscriminator.cs
index 40e782615..f57b44e54 100644
--- a/src/NJsonSchema/OpenApiDiscriminator.cs
+++ b/src/NJsonSchema/OpenApiDiscriminator.cs
@@ -37,11 +37,11 @@ public class OpenApiDiscriminator
public void AddMapping(Type type, JsonSchema schema)
{
var getDiscriminatorValueMethod = JsonInheritanceConverter?.GetType()
- .GetRuntimeMethod("GetDiscriminatorValue", new Type[] { typeof(Type) });
+ .GetRuntimeMethod("GetDiscriminatorValue", [typeof(Type)]);
if (getDiscriminatorValueMethod != null)
{
- var discriminatorValue = (string)getDiscriminatorValueMethod.Invoke(JsonInheritanceConverter, new[] { type } )!;
+ var discriminatorValue = (string)getDiscriminatorValueMethod.Invoke(JsonInheritanceConverter, [type])!;
Mapping[discriminatorValue] = new JsonSchema { Reference = schema.ActualSchema };
}
else
diff --git a/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs b/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs
index 22f4add90..b544c9150 100644
--- a/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs
+++ b/src/NJsonSchema/Validation/FormatValidators/DateTimeFormatValidator.cs
@@ -15,7 +15,8 @@ namespace NJsonSchema.Validation.FormatValidators
/// Validator for DateTime format.
public class DateTimeFormatValidator : IFormatValidator
{
- private readonly string[] _acceptableFormats = new [] {
+ private readonly string[] _acceptableFormats =
+ [
"yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK",
"yyyy-MM-dd' 'HH:mm:ss.FFFFFFFK",
"yyyy-MM-dd'T'HH:mm:ssK",
@@ -31,7 +32,7 @@ public class DateTimeFormatValidator : IFormatValidator
"yyyyMMdd",
"yyyy-MM",
"yyyy"
- };
+ ];
/// Gets the format attribute's value.
public string Format { get; } = JsonFormatStrings.DateTime;
diff --git a/src/NJsonSchema/Validation/JsonSchemaValidator.cs b/src/NJsonSchema/Validation/JsonSchemaValidator.cs
index 1eef4442b..0b2d6e009 100644
--- a/src/NJsonSchema/Validation/JsonSchemaValidator.cs
+++ b/src/NJsonSchema/Validation/JsonSchemaValidator.cs
@@ -49,15 +49,13 @@ public JsonSchemaValidator(JsonSchemaValidatorSettings? settings)
/// The list of validation errors.
public ICollection Validate(string jsonData, JsonSchema schema, SchemaType schemaType = SchemaType.JsonSchema)
{
- using (var reader = new StringReader(jsonData))
- using (var jsonReader = new JsonTextReader(reader)
+ using var reader = new StringReader(jsonData);
+ using var jsonReader = new JsonTextReader(reader)
{
DateParseHandling = DateParseHandling.None
- })
- {
- var jsonObject = JToken.ReadFrom(jsonReader);
- return Validate(jsonObject, schema, schemaType);
- }
+ };
+ var jsonObject = JToken.ReadFrom(jsonReader);
+ return Validate(jsonObject, schema, schemaType);
}
/// Validates the given JSON token.
@@ -417,7 +415,7 @@ private static string GetPropertyPath(string propertyPath, string propertyName)
return !string.IsNullOrEmpty(propertyPath) ? propertyPath + "." + propertyName : propertyName;
}
- private static void ValidateMaxProperties(JToken token, IList properties, JsonSchema schema, string? propertyName, string propertyPath, List errors)
+ private static void ValidateMaxProperties(JToken token, List properties, JsonSchema schema, string? propertyName, string propertyPath, List errors)
{
if (schema.MaxProperties > 0 && properties.Count > schema.MaxProperties)
{
@@ -425,7 +423,7 @@ private static void ValidateMaxProperties(JToken token, IList propert
}
}
- private static void ValidateMinProperties(JToken token, IList properties, JsonSchema schema, string? propertyName, string propertyPath, List errors)
+ private static void ValidateMinProperties(JToken token, List properties, JsonSchema schema, string? propertyName, string propertyPath, List errors)
{
if (schema.MinProperties > 0 && properties.Count < schema.MinProperties)
{
diff --git a/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs b/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs
index 361e91a1e..9ff4c5c9c 100644
--- a/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs
+++ b/src/NJsonSchema/Validation/JsonSchemaValidatorOptions.cs
@@ -12,8 +12,8 @@ public class JsonSchemaValidatorSettings
public StringComparer PropertyStringComparer { get; set; } = StringComparer.Ordinal;
/// Gets or sets the format validators.
- public IEnumerable FormatValidators { get; set; } = new IFormatValidator[]
- {
+ public IEnumerable FormatValidators { get; set; } =
+ [
new DateTimeFormatValidator(),
new DateFormatValidator(),
new EmailFormatValidator(),
@@ -27,7 +27,7 @@ public class JsonSchemaValidatorSettings
new ByteFormatValidator(),
new Base64FormatValidator(),
new UuidFormatValidator()
- };
+ ];
///
/// Adds a custom format validator to the array.
@@ -37,7 +37,7 @@ public void AddCustomFormatValidator(IFormatValidator formatValidator)
{
FormatValidators = this
.FormatValidators
- .Union(new[] { formatValidator })
+ .Union([formatValidator])
.ToArray();
}
}