Search code examples
c#jsonjson.netjsonschemanjsonschema

JSON Schema to C#


I am looking for a class or tool to convert JSON schema into a C# class as a prebuild step.

I have found several "home-brew" solutions (jsonschema.net, NJsonSchema, ...) , but would prefer to use some mature / official code related to a company / project. I understand that the Newtonsoft.json.Schema package is only able to do it the other way round (C# Class -> JSON)

I have surprisingly found that Visual Studio is able to do this out-of-the box using "Edit -> Paste Special -> Paste JSON as classes". Is the code/class/executable/dll that is behind this feature some how accessible programmatically for a pre-build step?


Solution

  • As @Stiefel mentioned, you can use nswag for this. First add the NSwag.MSBuild nuget package to your project, which also allows you to used the $(NSwagExe) macro to refer to nswag. Then, add a pre-build step to your project, in my case it looks like this:

    <Target Name="PreBuild" BeforeTargets="PreBuildEvent">
        <Exec Command="$(NSwagExe) jsonschema2csclient /name:Manifest /namespace:ManifestCreator.Models /input:$(SolutionDir)schemas\SingleFileSchema.0.1.0.json /output:$(ProjectDir)Models\ManifestSchema.cs" />
    </Target>