RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.7k stars 1.24k forks source link

For Dictionary<int,int> the generated one is: Dictionary<string, int>. Would <int,int> be possible? #4378

Open FrankDzaebel opened 1 year ago

FrankDzaebel commented 1 year ago

The aim is: to generate the expected Dictionary<int,int> type and not the Dictionary<string, int> as a property type. How can i reach my goal?

internal class IntDictionaryTestNSwag
{
    [Test]
    public void TestIntIntDictionaryGeneration()
    {
        // Arrange
        var schema = JsonSchema.FromType<TestClassInt2Dictionary>();
        var generator = new CSharpGenerator(schema);

        // Act
        var code = generator.GenerateFile();

        // Assert
        Assert.IsTrue(code.Contains("IDictionary<int, int?>"));
    }
}

public class TestClassInt2Dictionary
{
    public Dictionary<int, int?> IntIntDictProp { get; set; } = new();
}
FrankDzaebel commented 1 year ago

This would work:

    [Test]
    public void TestIntIntDictionaryGeneration_DictionaryKey_Works()
    {
        // Arrange
        var schema = JsonSchema.FromType<TestClassInt2Dictionary>();
        FixPropertiesWithDictionaryKey(schema);
        var data = schema.ToJson();

        // Act
        var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings());
        var code = generator.GenerateFile("MyClass");

        // Assert
        Assert.That(code.Contains("IDictionary<int, int?> IntIntDictProp "));
    }

    public class TestClassInt2Dictionary
    {
        public Dictionary<int, int?> IntIntDictProp { get; set; } = new();
    }

    private static void FixPropertiesWithDictionaryKey(JsonSchema schema)
    {
        foreach (var property in schema.Properties)
        {
            if (!property.Value.IsDictionary) { continue; }

            var typeProperty = typeof(TestClassInt2Dictionary).GetProperty(property.Key);
            if (typeProperty == null) { continue; }
            var keyType = typeProperty.PropertyType.GenericTypeArguments[0];
            property.Value.DictionaryKey = JsonSchema.FromType(keyType);
        }
    }