Reputation: 2793
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?
Upvotes: 4
Views: 2835
Reputation: 1648
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>
Upvotes: 5
Reputation: 9946
You should be able to do this with Visual Studio template transformation (T4) files. A couple years ago I used them for a similar scenario -- generating C# service proxy classes from a proprietary WSDL-like XML format. Unfortunately I don't have access to the code any more, but it's pretty easy to figure out once you start Googling for T4 and codegen.
You may also want to take a look at the extensibility / automation model, aka DTE to figure out whether you can access the built-in feature (which I'd launch from a T4).
T4 is really meant for single files (hence "template") but you can just as easily kick off template "builds" from the IDE that generate multiple files. The high-level is that you'll import helper assemblies like Json.Net to read the inputs, then use regular old file I/O to write the new files. There isn't much magic to it. DTE can do things like kick off external processes or present concatenated build logs for human review upon completion.
A couple caveats: I haven't used T4 in VS2017 yet, but I've read it requires extra steps to start using them, and if you are on an earlier VS there is apparently an issue where they don't initially load with your project after you migrate to VS2017.
Upvotes: 1