Skip to content

Commit 87b9df0

Browse files
committed
Allow setting x-csharp-existing-type on schemas
to override default resolved type
1 parent ed250a8 commit 87b9df0

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Xunit;
4+
5+
namespace NJsonSchema.CodeGeneration.CSharp.Tests;
6+
7+
public class ResolveExistingTypeTests
8+
{
9+
[Fact]
10+
public async Task String_schema_can_use_existing_type()
11+
{
12+
var json = @"{
13+
""type"": ""object"",
14+
""properties"": {
15+
""ip"": {
16+
""type"": ""string"",
17+
""pattern"": ""^\\d{1,3}(\\.\\d{1,3}){3}$"",
18+
""x-csharp-existing-type"": ""System.Net.IPAddress""
19+
}
20+
}
21+
}";
22+
23+
var schema = await JsonSchema.FromJsonAsync(json);
24+
25+
// Act
26+
var code = new CSharpGenerator(schema).GenerateFile("MyClass");
27+
28+
//// Act
29+
Assert.Contains("public System.Net.IPAddress Ip { get; set; }", code);
30+
}
31+
32+
[Fact]
33+
public async Task String_schema_can_use_existing_type_in_definition()
34+
{
35+
var json = @"{
36+
""type"": ""object"",
37+
""properties"": {
38+
""ip"": { ""$ref"": ""#/definitions/ip"" }
39+
},
40+
""definitions"": {
41+
""ip"": {
42+
""type"": ""string"",
43+
""pattern"": ""^\\d{1,3}(\\.\\d{1,3}){3}$"",
44+
""x-csharp-existing-type"": ""System.Net.IPAddress""
45+
}
46+
}
47+
}";
48+
49+
var schema = await JsonSchema.FromJsonAsync(json);
50+
51+
// Act
52+
var code = new CSharpGenerator(schema).GenerateFile("MyClass");
53+
54+
//// Act
55+
Assert.Contains("public System.Net.IPAddress Ip { get; set; }", code);
56+
}
57+
}

src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,12 @@ schema is JsonSchemaProperty property &&
7777

7878
var markAsNullableType = Settings.GenerateNullableReferenceTypes && isNullable;
7979

80+
if (schema.ExtensionData != null &&
81+
schema.ExtensionData.TryGetValue("x-csharp-existing-type", out var cSharpExistingType))
82+
{
83+
return cSharpExistingType + (markAsNullableType ? "?" : "");
84+
}
85+
8086
if (schema.ActualTypeSchema.IsAnyType &&
8187
schema.ActualDiscriminator == null &&
8288
schema.InheritedSchema == null && // not in inheritance hierarchy

0 commit comments

Comments
 (0)