Do you have a C# codebase with model classes for a JSON API? Did you ever have to use that API with another programming language, wishing there was a way to automatically convert your C# model to that other language? With quicktype and Json.NET, there is!
In this post I'll show you how to convert your C# model to Swift, but if you'd rather watch than read, here's a video that shows how to do it in one minute, for a model in this Open Source project:
One piece of the puzzle is Newtonsoft's JSON Schema package, which has a feature to generate a JSON Schema from a C# model class. That schema then serves as input to quicktype, which will generate the equivalent model classes in your favorite programming language. These are the steps to swift success:
Add the Json.Schema NuGet package to your project.
Put this code somewhere it will run. As a one-off, you can just do it first thing in your
Mainmethod, like I showed in the video. If you want the option to run it again, maybe because you foresee that the model might change, you might even want to make a separate project just to run it:
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(MyModelClass));
- Run the code. You should now have a
schema.jsonfile that you can copy and paste into quicktype. Pick whichever programming language you need the model in, and witness the magic!