Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting x-csharp-existing-type on schemas #1605

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ public string Resolve(JsonSchema schema, bool isNullable, string typeNameHint, b

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