Skip to content

Commit

Permalink
Allow setting x-cSharpExistingType on schemas
Browse files Browse the repository at this point in the history
to override default resolved type
  • Loading branch information
NaridaL committed Jun 10, 2023
1 parent ed250a8 commit 0a0a456
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
}
}
6 changes: 6 additions & 0 deletions src/NJsonSchema.CodeGeneration.CSharp/CSharpTypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 0a0a456

Please sign in to comment.