diff --git a/src/NJsonSchema.CodeGeneration.CSharp.Tests/ResolveExistingTypeTests.cs b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ResolveExistingTypeTests.cs new file mode 100644 index 000000000..9c82ed615 --- /dev/null +++ b/src/NJsonSchema.CodeGeneration.CSharp.Tests/ResolveExistingTypeTests.cs @@ -0,0 +1,57 @@ +using System; +using System.Threading.Tasks; +using Xunit; + +namespace NJsonSchema.CodeGeneration.CSharp.Tests; + +public class ResolveExistingTypeTests +{ + [Fact] + public async Task String_schema_can_use_existing_type() + { + var json = @"{ + ""type"": ""object"", + ""properties"": { + ""ip"": { + ""type"": ""string"", + ""pattern"": ""^\\d{1,3}(\\.\\d{1,3}){3}$"", + ""x-cSharpExistingType"": ""System.Net.IPAddress"" + } + } + }"; + + var schema = await JsonSchema.FromJsonAsync(json); + + // Act + var code = new CSharpGenerator(schema).GenerateFile("MyClass"); + + //// Act + Assert.Contains("public System.Net.IPAddress Ip { get; set; }", code); + } + + [Fact] + public async Task String_schema_can_use_existing_type_in_definition() + { + var json = @"{ + ""type"": ""object"", + ""properties"": { + ""ip"": { ""$ref"": ""#/definitions/ip"" } + }, + ""definitions"": { + ""ip"": { + ""type"": ""string"", + ""pattern"": ""^\\d{1,3}(\\.\\d{1,3}){3}$"", + ""x-cSharpExistingType"": ""System.Net.IPAddress"" + } + } + }"; + + var schema = await JsonSchema.FromJsonAsync(json); + + // Act + var code = new CSharpGenerator(schema).GenerateFile("MyClass"); + + //// Act + Assert.Contains("public System.Net.IPAddress Ip { get; set; }", code); + } +} diff --git a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs index eced21708..c08fa1533 100644 --- a/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs +++ b/src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs @@ -77,6 +77,12 @@ schema is JsonSchemaProperty property && var markAsNullableType = Settings.GenerateNullableReferenceTypes && isNullable; + if (schema.ExtensionData != null && + schema.ExtensionData.TryGetValue("x-cSharpExistingType", out var cSharpExistingType)) + { + return cSharpExistingType + (markAsNullableType ? "?" : ""); + } + if (schema.ActualTypeSchema.IsAnyType && schema.ActualDiscriminator == null && schema.InheritedSchema == null && // not in inheritance hierarchy