RicoSuter / NJsonSchema

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

Add C# Source Generator #1726

Open valchetski opened 2 weeks ago

valchetski commented 2 weeks ago

What's in this PR

This change aims to add a C# Source generator that automatically creates classes based on JSON schema. The idea is to make code generation more straightforward for generic scenarios. I've tried that approach on my project and it worked quite well. I thought it'd be good to make it a part of the library. This Source Generator has few configurable properties and can be extended in the future if needed.

Current approach

To generate C# classes you need to create a separate console project that will generate a .cs file and put it somewhere in your Solution. Then you need to manually run that console application to generate/regenerate the models. Here's example

New (additional) approach

Add the following elements in the .csproj file of your project where the generated .cs file will exist:

  <ItemGroup>
    <PackageReference Include="NJsonSchema.SourceGenerators.CSharp" />
  </ItemGroup>

  <ItemGroup>
    <AdditionalFiles 
        Include="schema.json" 
        NJsonSchema_GenerateOptionalPropertiesAsNullable="true" 
        NJsonSchema_Namespace="NJsonSchema.Demo.Generated" 
        NJsonSchema_TypeNameHint="PersonGenerated" 
        NJsonSchema_FileName="Person.g.cs" />
  </ItemGroup>

After that Source Generator will automatically create a .cs file during compilation. No additional console project or manual job is needed.

Concerns

I have some questions/concerns regarding the implementation and have put them in the comments. We can start from this main one.

Also added some explanatory comments about why something was implemented that way. As tooling for the Source Generators is not the best for now and there is a lot of msbuild magic in the .csproj files.