RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.4k stars 535 forks source link

Generate multiple output artifacts instead of one output file (code generators)? #1554

Open KseniyaYudina opened 2 years ago

KseniyaYudina commented 2 years ago

Is it possible to generate controllers in multiple output files instead of just one? Trying to use CustomCSharpControllerGenerator, CSharpControllerGeneratorSettings in NSwag.CodeGeneration.CSharp.

thucnguyen77 commented 2 years ago

Here is the code that I wrote for that purpose. Hope it'd help.

using NJsonSchema;
using NJsonSchema.CodeGeneration.CSharp;

var jsonSchema = File.ReadAllText("Schema/AllSchemas.json");

var schema = await JsonSchema.FromJsonAsync(jsonSchema);

var settings = new CSharpGeneratorSettings()
{
    Namespace = "Library.ObjectModel",
    GenerateDataAnnotations = false,
    GenerateJsonMethods = true,
};

var generator = new CSharpGenerator(schema, settings);
var generatedTypeNames = new List<string>();

var types = generator.GenerateTypes(schema, "").ToList();
//var types = generator.GenerateTypes().ToList();

foreach (var type in types)
{
    if (generatedTypeNames.Contains(type.TypeName)) continue;
    Console.WriteLine($"Generating {type.TypeName}");
    File.WriteAllText($"Code/{type.TypeName}.cs", PreProcess(type.Code));
    generatedTypeNames.Add(type.TypeName);
}

string PreProcess(string code)
{
    return code;
}

Note: You can add any processing to PreProcess method.

Another note is that the line var types = generator.GenerateTypes().ToList(); won't work.