diff --git a/Directory.Build.props b/Directory.Build.props
index aca9fbb92..ccc140a26 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,31 +1,44 @@
-
- 11.0.0
-
- Rico Suter
- Copyright © Rico Suter, 2022
-
- True
- ../NJsonSchema.snk
-
- json schema validation generator .net
- http://NJsonSchema.org
- JSON Schema reader, generator and validator for .NET
- NuGetIcon.png
- MIT
-
- true
- true
- true
- snupkg
- True
-
- latest
- true
- enable
-
- true
-
-
+
+ 11.0.0
+
+ Rico Suter
+ Copyright © Rico Suter, 2022
+
+ True
+ ../NJsonSchema.snk
+
+ json schema validation generator .net
+ http://NJsonSchema.org
+ JSON Schema reader, generator and validator for .NET
+ NuGetIcon.png
+ MIT
+
+ true
+ true
+ true
+ snupkg
+ True
+
+ latest
+ true
+ enable
+
+ true
+
+
+
+
+ true
+ latest-Recommended
+ true
+
+ $(NoWarn);CA1200;CA1510;CA1716;CA1720
+
diff --git a/Directory.Packages.props b/Directory.Packages.props
index c7ac7a7fd..94d8c431d 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -5,10 +5,10 @@
-
+
-
+
@@ -18,13 +18,13 @@
-
-
-
+
+
+
-
-
+
+
\ No newline at end of file
diff --git a/src/NJsonSchema.Annotations/IJsonSchemaExtensionDataAttribute.cs b/src/NJsonSchema.Annotations/IJsonSchemaExtensionDataAttribute.cs
index d440dfc44..f6c42e608 100644
--- a/src/NJsonSchema.Annotations/IJsonSchemaExtensionDataAttribute.cs
+++ b/src/NJsonSchema.Annotations/IJsonSchemaExtensionDataAttribute.cs
@@ -11,7 +11,9 @@
namespace NJsonSchema.Annotations;
/// Interface to add an extension data property to a class or property, implementation needs to inherit from System.Attribute.
+#pragma warning disable CA1711 // Rename type name IJsonSchemaExtensionDataAttribute so that it does not end in 'Attribute'
public interface IJsonSchemaExtensionDataAttribute
+#pragma warning restore CA1711
{
/// Gets the extension data.
IReadOnlyDictionary ExtensionData { get; }
diff --git a/src/NJsonSchema.Benchmark/NJsonSchema.Benchmark.csproj b/src/NJsonSchema.Benchmark/NJsonSchema.Benchmark.csproj
index 1f7792c19..f889f9404 100644
--- a/src/NJsonSchema.Benchmark/NJsonSchema.Benchmark.csproj
+++ b/src/NJsonSchema.Benchmark/NJsonSchema.Benchmark.csproj
@@ -6,6 +6,7 @@
$(NoWarn),xUnit1013
false
disable
+ false
diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/NJsonSchema.CodeGeneration.CSharp.Tests.csproj b/src/NJsonSchema.CodeGeneration.CSharp.Tests/NJsonSchema.CodeGeneration.CSharp.Tests.csproj
index 408d7f362..d5ea2de05 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/NJsonSchema.CodeGeneration.CSharp.Tests.csproj
+++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/NJsonSchema.CodeGeneration.CSharp.Tests.csproj
@@ -6,6 +6,7 @@
true
$(NoWarn),1587,1998,1591,618,SYSLIB0012
disable
+ false
diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableReferenceTypesTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableReferenceTypesTests.cs
index a0c98bf78..f33422088 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableReferenceTypesTests.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/NullableReferenceTypesTests.cs
@@ -245,5 +245,48 @@ public async Task When_generating_from_json_schema_string_property_with_date_or_
Assert.Contains("public string Required { get; set; } = default!;", code);
Assert.Contains("public string? Optional { get; set; } = default!;", code);
}
+
+ [Fact]
+ public async Task
+ When_generating_from_json_schema_string_property_with_reference_is_optional_and_GenerateNullableOptionalProperties_is_set_then_CSharp_property()
+ {
+ //// Arrange
+ var schemaJson = @"
+ {
+ ""type"": ""object"",
+ ""required"": [
+ ""required""
+ ],
+ ""properties"": {
+ ""required"": { ""$ref"": ""#/$defs/requiredString"" },
+ ""optional"": { ""$ref"": ""#/$defs/optionalString"" }
+ },
+ ""$defs"": {
+ ""requiredString"": { ""type"": ""string"" },
+ ""optionalString"": { ""type"": ""string"" }
+ }
+ }
+ ";
+
+ var schema = await JsonSchema.FromJsonAsync(schemaJson);
+
+ //// Act
+ var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
+ {
+ ClassStyle = CSharpClassStyle.Poco,
+ SchemaType = SchemaType.OpenApi3,
+ DateType = "string",
+ DateTimeType = "string",
+ TimeType = "string",
+ TimeSpanType = "string",
+ GenerateNullableReferenceTypes = true,
+ GenerateOptionalPropertiesAsNullable = true
+ });
+ var code = generator.GenerateFile("MyClass");
+
+ //// Assert
+ Assert.Contains("public string Required { get; set; } = default!;", code);
+ Assert.Contains("public string? Optional { get; set; } = default!;", code);
+ }
}
}
\ No newline at end of file
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
index 285e6a221..de2fd2574 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpGenerator.cs
@@ -81,13 +81,13 @@ public override IEnumerable GenerateTypes()
}
///
- protected override string GenerateFile(IEnumerable artifactCollection)
+ protected override string GenerateFile(IEnumerable artifacts)
{
var model = new FileTemplateModel
{
Namespace = Settings.Namespace ?? string.Empty,
GenerateNullableReferenceTypes = Settings.GenerateNullableReferenceTypes,
- TypesCode = artifactCollection.Concatenate()
+ TypesCode = artifacts.Concatenate()
};
var template = Settings.TemplateFactory.CreateTemplate("CSharp", "File", model);
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs
index 1f13fd59e..815d8dd68 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpJsonSerializerGenerator.cs
@@ -22,7 +22,7 @@ public static class CSharpJsonSerializerGenerator
public static string GenerateJsonSerializerParameterCode(CSharpGeneratorSettings settings, IEnumerable? additionalJsonConverters)
{
var jsonConverters = GetJsonConverters(settings, additionalJsonConverters);
- var hasJsonConverters = jsonConverters.Any();
+ var hasJsonConverters = jsonConverters.Count > 0;
return GenerateForJsonLibrary(settings, jsonConverters, hasJsonConverters);
}
@@ -95,24 +95,17 @@ private static string GenerateForJsonLibrary(CSharpGeneratorSettings settings, L
private static string GenerateConverters(List jsonConverters, CSharpJsonLibrary jsonLibrary)
{
- if (jsonConverters.Any())
+ if (jsonConverters.Count > 0)
{
- switch (jsonLibrary)
+ return jsonLibrary switch
{
- case CSharpJsonLibrary.NewtonsoftJson:
- return "new Newtonsoft.Json.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }";
-
- case CSharpJsonLibrary.SystemTextJson:
- return "new System.Text.Json.Serialization.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }";
-
- default: // TODO: possibly add more json converters
- return string.Empty;
- }
- }
- else
- {
- return string.Empty;
+ CSharpJsonLibrary.NewtonsoftJson => "new Newtonsoft.Json.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }",
+ CSharpJsonLibrary.SystemTextJson => "new System.Text.Json.Serialization.JsonConverter[] { " + string.Join(", ", jsonConverters.Select(c => "new " + c + "()")) + " }",
+ _ => string.Empty
+ };
}
+
+ return string.Empty;
}
}
}
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs
index 2c61c752f..2a42c6df8 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpPropertyNameGenerator.cs
@@ -11,7 +11,7 @@ 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[] _reservedFirstPassChars = { '"', '\'', '@', '?', '!', '$', '[', ']', '(', ')', '.', '=', '+', '|' };
private static readonly char[] _reservedSecondPassChars = { '*', ':', '-', '#', '&' };
/// Generates the property name.
@@ -35,7 +35,8 @@ public string Generate(JsonSchemaProperty property)
.Replace(")", string.Empty)
.Replace(".", "-")
.Replace("=", "-")
- .Replace("+", "plus");
+ .Replace("+", "plus")
+ .Replace("|", "_");
}
name = ConversionUtilities.ConvertToUpperCamelCase(name, true);
@@ -53,4 +54,4 @@ public string Generate(JsonSchemaProperty property)
return name;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
index 13ddb5ef5..5f329158e 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
@@ -60,13 +60,6 @@ public string Resolve(JsonSchema schema, bool isNullable, string? typeNameHint,
throw new ArgumentNullException(nameof(schema));
}
- schema = GetResolvableSchema(schema);
-
- if (schema == ExceptionSchema)
- {
- return "System.Exception";
- }
-
// Primitive schemas (no new type)
if (Settings.GenerateOptionalPropertiesAsNullable &&
schema is JsonSchemaProperty property &&
@@ -75,6 +68,13 @@ schema is JsonSchemaProperty property &&
isNullable = true;
}
+ schema = GetResolvableSchema(schema);
+
+ if (schema == ExceptionSchema)
+ {
+ return "System.Exception";
+ }
+
var markAsNullableType = Settings.GenerateNullableReferenceTypes && isNullable;
if (schema.ActualTypeSchema.IsAnyType &&
@@ -217,7 +217,7 @@ private static string ResolveBoolean(bool isNullable)
return isNullable ? "bool?" : "bool";
}
- private string ResolveInteger(JsonSchema schema, bool isNullable, string? typeNameHint)
+ private static string ResolveInteger(JsonSchema schema, bool isNullable, string? typeNameHint)
{
if (schema.Format == JsonFormatStrings.Byte)
{
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
index 851724d8d..07356edf9 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpValueGenerator.cs
@@ -67,11 +67,11 @@ public CSharpValueGenerator(CSharpGeneratorSettings settings)
if (schema.Type.IsArray() ||
schema.Type.IsObject())
{
- targetType = !string.IsNullOrEmpty(_settings.DictionaryInstanceType) && targetType.StartsWith(_settings.DictionaryType + "<")
+ targetType = !string.IsNullOrEmpty(_settings.DictionaryInstanceType) && targetType.StartsWith(_settings.DictionaryType + "<", StringComparison.Ordinal)
? _settings.DictionaryInstanceType + targetType.Substring(_settings.DictionaryType.Length)
: targetType;
- targetType = !string.IsNullOrEmpty(_settings.ArrayInstanceType) && targetType.StartsWith(_settings.ArrayType + "<")
+ targetType = !string.IsNullOrEmpty(_settings.ArrayInstanceType) && targetType.StartsWith(_settings.ArrayType + "<", StringComparison.Ordinal)
? _settings.ArrayInstanceType + targetType.Substring(_settings.ArrayType.Length)
: targetType;
@@ -93,11 +93,11 @@ public override string GetNumericValue(JsonObjectType type, object value, string
switch (format)
{
case JsonFormatStrings.Byte:
- return "(byte)" + Convert.ToByte(value).ToString(CultureInfo.InvariantCulture);
+ return "(byte)" + Convert.ToByte(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
case JsonFormatStrings.Integer:
- return Convert.ToInt32(value).ToString(CultureInfo.InvariantCulture);
+ return Convert.ToInt32(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
case JsonFormatStrings.Long:
- return Convert.ToInt64(value) + "L";
+ return Convert.ToInt64(value, CultureInfo.InvariantCulture) + "L";
case JsonFormatStrings.Double:
return ConvertNumberToString(value) + "D";
case JsonFormatStrings.Float:
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs
index ef3983f1b..7c44e0ada 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs
@@ -6,6 +6,7 @@
// Rico Suter, mail@rsuter.com
//-----------------------------------------------------------------------
+using System;
using System.Collections.Generic;
using System.Linq;
using NJsonSchema.CodeGeneration.Models;
@@ -145,7 +146,7 @@ public ClassTemplateModel(string typeName, CSharpGeneratorSettings settings,
_schema?.InheritsSchema(_resolver.ExceptionSchema) == true;
/// Gets a value indicating whether to use the DateFormatConverter.
- public bool UseDateFormatConverter => _settings.DateType.StartsWith("System.DateTime");
+ public bool UseDateFormatConverter => _settings.DateType.StartsWith("System.DateTime", StringComparison.Ordinal);
/// Gets or sets the access modifier of generated classes and interfaces.
public string TypeAccessModifier => _settings.TypeAccessModifier;
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs
index efc2698bb..0855e9936 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs
+++ b/src/NJsonSchema.CodeGeneration.CSharp/Models/EnumTemplateModel.cs
@@ -8,6 +8,7 @@
using NJsonSchema.Annotations;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using NJsonSchema.CodeGeneration.Models;
@@ -78,8 +79,8 @@ public IEnumerable Enums
{
Name = _settings.EnumNameGenerator.Generate(i, name, value, _schema),
Value = value.ToString(),
- InternalValue = valueInt64.ToString(),
- InternalFlagValue = valueInt64.ToString()
+ InternalValue = valueInt64.ToString(CultureInfo.InvariantCulture),
+ InternalFlagValue = valueInt64.ToString(CultureInfo.InvariantCulture)
});
}
else
@@ -89,7 +90,7 @@ public IEnumerable Enums
Name = _settings.EnumNameGenerator.Generate(i, name, value, _schema),
Value = value.ToString(),
InternalValue = value.ToString(),
- InternalFlagValue = (1 << i).ToString()
+ InternalFlagValue = (1 << i).ToString(CultureInfo.InvariantCulture)
});
}
}
@@ -102,8 +103,8 @@ public IEnumerable Enums
{
Name = _settings.EnumNameGenerator.Generate(i, name, value, _schema),
Value = value.ToString(),
- InternalValue = i.ToString(),
- InternalFlagValue = (1 << i).ToString()
+ InternalValue = i.ToString(CultureInfo.InvariantCulture),
+ InternalFlagValue = (1 << i).ToString(CultureInfo.InvariantCulture)
});
}
}
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Annotations.liquid b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Annotations.liquid
new file mode 100644
index 000000000..5f282702b
--- /dev/null
+++ b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Annotations.liquid
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Member.Annotations.liquid b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Member.Annotations.liquid
new file mode 100644
index 000000000..5f282702b
--- /dev/null
+++ b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.Member.Annotations.liquid
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.liquid b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.liquid
index 849187e90..57956c084 100644
--- a/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.liquid
+++ b/src/NJsonSchema.CodeGeneration.CSharp/Templates/Enum.liquid
@@ -7,12 +7,14 @@
{%- if IsEnumAsBitFlags -%}
[System.Flags]
{%- endif -%}
+{%- template Enum.Annotations -%}
{{ TypeAccessModifier }} enum {{ Name }}{%- if HasExtendedValueRange %} : long{% endif %}
{
{%- for enum in Enums %}
{%- if IsStringEnum -%}
[System.Runtime.Serialization.EnumMember(Value = @"{{ enum.Value | replace: '"', '""' }}")]
{%- endif -%}
+{%- template Enum.Member.Annotations -%}
{%- if IsEnumAsBitFlags -%}
{{ enum.Name }} = {{ enum.InternalFlagValue }},
{%- else -%}
diff --git a/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj b/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj
index 08c8252c0..641305b15 100644
--- a/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj
+++ b/src/NJsonSchema.CodeGeneration.Tests/NJsonSchema.CodeGeneration.Tests.csproj
@@ -5,6 +5,7 @@
false
$(NoWarn),1998,1591,618
disable
+ false
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NJsonSchema.CodeGeneration.TypeScript.Tests.csproj b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NJsonSchema.CodeGeneration.TypeScript.Tests.csproj
index 356f35ade..c2dc07531 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NJsonSchema.CodeGeneration.TypeScript.Tests.csproj
+++ b/src/NJsonSchema.CodeGeneration.TypeScript.Tests/NJsonSchema.CodeGeneration.TypeScript.Tests.csproj
@@ -6,6 +6,7 @@
true
$(NoWarn),1587,1998,1591,618
disable
+ false
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs
index ce5923a35..672bcd731 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/DataConversionGenerator.cs
@@ -147,7 +147,7 @@ private static string GetStringToDateTime(DataConversionParameters parameters, J
return "dayjs";
default:
- throw new ArgumentOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(parameters));
}
}
@@ -168,7 +168,7 @@ private static string GetDateToString(DataConversionParameters parameters, JsonS
return "toFormat('yyyy-MM-dd')";
default:
- throw new ArgumentOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(parameters));
}
}
@@ -207,7 +207,7 @@ private static string GetDateTimeToString(DataConversionParameters parameters, J
return "toISOString()";
default:
- throw new ArgumentOutOfRangeException();
+ throw new ArgumentOutOfRangeException(nameof(parameters));
}
}
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs b/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs
index 48ce8df29..963206f81 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/Models/ClassTemplateModel.cs
@@ -104,7 +104,7 @@ public string Inheritance
public bool GenerateConstructorInterface => _settings.GenerateConstructorInterface;
/// Gets or sets a value indicating whether POJO objects in the constructor data are converted to DTO instances (default: true).
- public bool ConvertConstructorInterfaceData => _settings.ConvertConstructorInterfaceData && Properties.Any(p => p.SupportsConstructorConversion);
+ public bool ConvertConstructorInterfaceData => _settings.ConvertConstructorInterfaceData && Properties.Exists(p => p.SupportsConstructorConversion);
/// Gets the null value.
public string NullValue => _settings.NullValue.ToString().ToLowerInvariant();
@@ -134,13 +134,13 @@ public string IndexerPropertyValueType
public bool HandleReferences => _settings.HandleReferences;
/// Gets a value indicating whether the type has properties.
- public bool HasProperties => Properties.Any();
+ public bool HasProperties => Properties.Count > 0;
/// Gets the property models.
public List Properties { get; }
/// Gets a value indicating whether any property has a default value.
- public bool HasDefaultValues => Properties.Any(p => p.HasDefaultValue);
+ public bool HasDefaultValues => Properties.Exists(p => p.HasDefaultValue);
/// Gets a value indicating whether
public bool RequiresStrictPropertyInitialization => _settings.RequiresStrictPropertyInitialization;
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs
index 2b74f1f10..f6f5c9a0b 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptGenerator.cs
@@ -146,7 +146,9 @@ protected override CodeArtifact GenerateType(JsonSchema schema, string typeNameH
}
else
{
+#pragma warning disable CA2208
throw new ArgumentOutOfRangeException(nameof(Settings.EnumStyle), Settings.EnumStyle, "Unknown enum style");
+#pragma warning restore CA2208
}
var template = Settings.TemplateFactory.CreateTemplate("TypeScript", templateName, model);
diff --git a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs
index b1821edf1..b61f02fd2 100644
--- a/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs
+++ b/src/NJsonSchema.CodeGeneration.TypeScript/TypeScriptTypeResolver.cs
@@ -56,7 +56,9 @@ public override string Resolve(JsonSchema schema, bool isNullable, string? typeN
/// Gets a value indicating whether the schema supports constructor conversion.
/// The schema.
/// The result.
+#pragma warning disable CA1822
public bool SupportsConstructorConversion(JsonSchema? schema)
+#pragma warning restore CA1822
{
return schema?.ActualSchema.ResponsibleDiscriminatorObject == null;
}
@@ -109,7 +111,7 @@ private string Resolve(JsonSchema schema, string? typeNameHint, bool addInterfac
if (type.IsInteger() && !schema.ActualTypeSchema.IsEnumeration)
{
- return ResolveInteger(schema.ActualTypeSchema, typeNameHint);
+ return TypeScriptTypeResolver.ResolveInteger(schema.ActualTypeSchema, typeNameHint);
}
if (type.IsBoolean())
@@ -167,7 +169,9 @@ private string Resolve(JsonSchema schema, string? typeNameHint, bool addInterfac
return $"{{ [key in {keyType}]?: {valueType}; }}";
}
+#pragma warning disable CA2208
throw new ArgumentOutOfRangeException(nameof(Settings.EnumStyle), Settings.EnumStyle, "Unknown enum style");
+#pragma warning restore CA2208
}
return $"{{ [key: {keyType}]: {valueType}; }}";
@@ -290,7 +294,7 @@ private string ResolveString(JsonSchema schema, string? typeNameHint)
return "string";
}
- private string ResolveInteger(JsonSchema schema, string? typeNameHint)
+ private static string ResolveInteger(JsonSchema schema, string? typeNameHint)
{
return "number";
}
diff --git a/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs b/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
index ddc19fc96..e53f6f4e3 100644
--- a/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
+++ b/src/NJsonSchema.CodeGeneration/CodeArtifactExtensions.cs
@@ -6,6 +6,7 @@
// Rico Suter, mail@rsuter.com
//-----------------------------------------------------------------------
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
@@ -69,7 +70,7 @@ public static IEnumerable OrderByBaseDependency(this IEnumerableRico Suter, mail@rsuter.com
//-----------------------------------------------------------------------
+using System;
using System.Text.RegularExpressions;
namespace NJsonSchema.CodeGeneration
@@ -29,48 +30,37 @@ public string Generate(int index, string? name, object? value, JsonSchema schema
return "Empty";
}
- switch (name)
+ name = name switch
{
- case ("="):
- name = "Eq";
- break;
- case ("!="):
- name = "Ne";
- break;
- case (">"):
- name = "Gt";
- break;
- case ("<"):
- name = "Lt";
- break;
- case (">="):
- name = "Ge";
- break;
- case ("<="):
- name = "Le";
- break;
- case ("~="):
- name = "Approx";
- break;
- }
+ "=" => "Eq",
+ "!=" => "Ne",
+ ">" => "Gt",
+ "<" => "Lt",
+ ">=" => "Ge",
+ "<=" => "Le",
+ "~=" => "Approx",
+ _ => name
+ };
- if (name!.StartsWith("-"))
+#pragma warning disable CS8604 // Possible null reference argument.
+ if (name.StartsWith('-'))
+#pragma warning restore CS8604 // Possible null reference argument.
{
name = "Minus" + name.Substring(1);
}
- if (name.StartsWith("+"))
+ if (name.StartsWith('+'))
{
name = "Plus" + name.Substring(1);
}
- if (name.StartsWith("_-"))
+ if (name.StartsWith("_-", StringComparison.Ordinal))
{
name = "__" + name.Substring(2);
}
return _invalidNameCharactersPattern.Replace(ConversionUtilities.ConvertToUpperCamelCase(name
- .Replace(":", "-").Replace(@"""", @""), true), "_");
+ .Replace(":", "-").Replace(@"""", ""), firstCharacterMustBeAlpha: true), "_");
}
}
}
diff --git a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs
index 348ccdb9c..2fc559c63 100644
--- a/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs
+++ b/src/NJsonSchema.CodeGeneration/DefaultTemplateFactory.cs
@@ -103,7 +103,7 @@ protected virtual string GetEmbeddedLiquidTemplate(string language, string templ
/// Could not load template.
private string GetLiquidTemplate(string language, string template)
{
- if (!template.EndsWith("!") && !string.IsNullOrEmpty(_settings.TemplateDirectory))
+ if (!template.EndsWith('!') && !string.IsNullOrEmpty(_settings.TemplateDirectory))
{
var templateFilePath = Path.Combine(_settings.TemplateDirectory, template + ".liquid");
if (File.Exists(templateFilePath))
diff --git a/src/NJsonSchema.CodeGeneration/ExtensionCode.cs b/src/NJsonSchema.CodeGeneration/ExtensionCode.cs
index cbcba205d..cbea11e2f 100644
--- a/src/NJsonSchema.CodeGeneration/ExtensionCode.cs
+++ b/src/NJsonSchema.CodeGeneration/ExtensionCode.cs
@@ -33,12 +33,12 @@ public abstract class ExtensionCode
/// The extension class is not defined.
public string GetExtensionClassBody(string className)
{
- if (!ExtensionClasses.ContainsKey(className))
+ if (!ExtensionClasses.TryGetValue(className, out string? value))
{
throw new InvalidOperationException("The extension class '" + className + "' is not defined.");
}
- var match = Regex.Match(ExtensionClasses[className], "(.*?)class (.*?){(.*)}", RegexOptions.Singleline);
+ var match = Regex.Match(value, "(.*?)class (.*?){(.*)}", RegexOptions.Singleline);
return match.Groups[3].Value;
}
}
diff --git a/src/NJsonSchema.CodeGeneration/NJsonSchema.CodeGeneration.csproj b/src/NJsonSchema.CodeGeneration/NJsonSchema.CodeGeneration.csproj
index b653ffa10..209852fbf 100644
--- a/src/NJsonSchema.CodeGeneration/NJsonSchema.CodeGeneration.csproj
+++ b/src/NJsonSchema.CodeGeneration/NJsonSchema.CodeGeneration.csproj
@@ -21,9 +21,8 @@
-
- EnumExtensions.cs
-
+
+
\ No newline at end of file
diff --git a/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs b/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs
index 5225df649..b390262ba 100644
--- a/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs
+++ b/src/NJsonSchema.CodeGeneration/ValueGeneratorBase.cs
@@ -6,7 +6,6 @@
// Rico Suter, mail@rsuter.com
//-----------------------------------------------------------------------
-using NJsonSchema.Annotations;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
@@ -18,7 +17,7 @@ namespace NJsonSchema.CodeGeneration
public abstract class ValueGeneratorBase
{
private readonly CodeGeneratorSettingsBase _settings;
- private readonly List _unsupportedFormatStrings = new List()
+ private readonly HashSet _unsupportedFormatStrings = new()
{
JsonFormatStrings.Date,
JsonFormatStrings.DateTime,
@@ -110,7 +109,9 @@ protected virtual string GetEnumDefaultValue(JsonSchema schema, JsonSchema actua
/// Gets the default value as string literal.
/// The schema.
/// The string literal.
+#pragma warning disable CA1822
protected string GetDefaultAsStringLiteral(JsonSchema schema)
+#pragma warning restore CA1822
{
return "\"" + ConversionUtilities.ConvertToStringLiteral(schema.Default?.ToString() ?? string.Empty) + "\"";
}
@@ -118,7 +119,9 @@ protected string GetDefaultAsStringLiteral(JsonSchema schema)
/// Converts a number to its string representation.
/// The value.
/// The string.
+#pragma warning disable CA1822
protected string ConvertNumberToString(object value)
+#pragma warning restore CA1822
{
if (value is byte)
{
diff --git a/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs b/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs
index 4e0fe72a3..e68a8a3ea 100644
--- a/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs
+++ b/src/NJsonSchema.NewtonsoftJson/Converters/JsonExceptionConverter.cs
@@ -67,7 +67,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer
if (value is not null)
{
- foreach (var property in GetExceptionProperties(value.GetType()))
+ foreach (var property in JsonExceptionConverter.GetExceptionProperties(value.GetType()))
{
var propertyValue = property.Key.GetValue(exception);
if (propertyValue != null)
@@ -109,7 +109,7 @@ public override bool CanConvert(Type objectType)
var newSerializer = new JsonSerializer();
newSerializer.ContractResolver = (IContractResolver)Activator.CreateInstance(serializer.ContractResolver.GetType());
- var field = GetField(typeof(DefaultContractResolver), "_sharedCache");
+ var field = JsonExceptionConverter.GetField(typeof(DefaultContractResolver), "_sharedCache");
if (field != null)
{
field.SetValue(newSerializer.ContractResolver, false);
@@ -130,7 +130,7 @@ public override bool CanConvert(Type objectType)
if (jObject.TryGetValue("discriminator", StringComparison.OrdinalIgnoreCase, out token))
{
var discriminator = token.Value();
- if (objectType.Name.Equals(discriminator) == false)
+ if (objectType.Name.Equals(discriminator, StringComparison.Ordinal) == false)
{
var exceptionType = Type.GetType("System." + discriminator, false);
if (exceptionType != null)
@@ -155,7 +155,7 @@ public override bool CanConvert(Type objectType)
var value = jObject.ToObject(objectType, newSerializer);
if (value is not null)
{
- foreach (var property in GetExceptionProperties(value.GetType()))
+ foreach (var property in JsonExceptionConverter.GetExceptionProperties(value.GetType()))
{
var jValue = jObject.GetValue(resolver.GetResolvedPropertyName(property.Value));
var propertyValue = (object?)jValue?.ToObject(property.Key.PropertyType);
@@ -167,14 +167,14 @@ public override bool CanConvert(Type objectType)
{
var fieldNameSuffix = property.Value.Substring(0, 1).ToLowerInvariant() + property.Value.Substring(1);
- field = GetField(objectType, "m_" + fieldNameSuffix);
+ field = JsonExceptionConverter.GetField(objectType, "m_" + fieldNameSuffix);
if (field != null)
{
field.SetValue(value, propertyValue);
}
else
{
- field = GetField(objectType, "_" + fieldNameSuffix);
+ field = JsonExceptionConverter.GetField(objectType, "_" + fieldNameSuffix);
if (field != null)
{
field.SetValue(value, propertyValue);
@@ -192,19 +192,25 @@ public override bool CanConvert(Type objectType)
return value;
}
- private FieldInfo? GetField(Type type, string fieldName)
+ private static FieldInfo? GetField(Type type, string fieldName)
{
var typeInfo = type.GetTypeInfo();
var field = typeInfo.GetDeclaredField(fieldName);
if (field == null && typeInfo.BaseType != null)
{
- return GetField(typeInfo.BaseType, fieldName);
+ return JsonExceptionConverter.GetField(typeInfo.BaseType, fieldName);
}
return field;
}
- private IDictionary GetExceptionProperties(Type exceptionType)
+
+ private static readonly HashSet ignoredExceptionProperties = new()
+ {
+ "Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult"
+ };
+
+ private static Dictionary GetExceptionProperties(Type exceptionType)
{
var result = new Dictionary();
foreach (var property in exceptionType.GetRuntimeProperties().Where(p => p.GetMethod?.IsPublic == true))
@@ -212,8 +218,7 @@ private IDictionary GetExceptionProperties(Type exceptionT
var attribute = property.GetCustomAttribute();
var propertyName = attribute != null ? attribute.PropertyName : property.Name;
- if (propertyName is not null &&
- !new[] { "Message", "StackTrace", "Source", "InnerException", "Data", "TargetSite", "HelpLink", "HResult" }.Contains(propertyName))
+ if (propertyName is not null && !ignoredExceptionProperties.Contains(propertyName))
{
result[property] = propertyName;
}
@@ -221,7 +226,7 @@ private IDictionary GetExceptionProperties(Type exceptionT
return result;
}
- private void SetExceptionFieldValue(JObject jObject, string propertyName, object value, string fieldName, IContractResolver resolver, JsonSerializer serializer)
+ private static void SetExceptionFieldValue(JObject jObject, string propertyName, object value, string fieldName, IContractResolver resolver, JsonSerializer serializer)
{
var field = typeof(Exception).GetTypeInfo().GetDeclaredField(fieldName);
var jsonPropertyName = resolver is DefaultContractResolver ? ((DefaultContractResolver)resolver).GetResolvedPropertyName(propertyName) : propertyName;
diff --git a/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs b/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs
index 9b31a8dbc..aff50579c 100644
--- a/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs
+++ b/src/NJsonSchema.NewtonsoftJson/Converters/JsonInheritanceConverter.cs
@@ -250,7 +250,7 @@ protected virtual Type GetDiscriminatorType(JObject jObject, Type objectType, st
throw new InvalidOperationException("Could not find subtype of '" + objectType.Name + "' with discriminator '" + discriminatorValue + "'.");
}
- private Type? GetSubtypeFromKnownTypeAttributes(Type objectType, string discriminator)
+ private static Type? GetSubtypeFromKnownTypeAttributes(Type objectType, string discriminator)
{
var type = objectType;
do
@@ -265,10 +265,10 @@ protected virtual Type GetDiscriminatorType(JObject jObject, Type objectType, st
}
else if (attribute.MethodName != null)
{
- var method = type.GetRuntimeMethod((string)attribute.MethodName, new Type[0]);
+ var method = type.GetRuntimeMethod((string)attribute.MethodName, Type.EmptyTypes);
if (method != null)
{
- var types = (System.Collections.Generic.IEnumerable)method.Invoke(null, new object[0]);
+ var types = (System.Collections.Generic.IEnumerable)method.Invoke(null, Array.Empty