The one sentence overview
Generate C# classes from a JSON response.
Why not just use var? Like everything in programming it depends.
For the application I am developing I like the comfort of compile time validation along with the ability to lean on IntelliSense when I need to.
What I used
- Visual Studio 2019 Community Edition Version 16.4.5
- Newtonsoft Json.NET 12.0.3
- Obtain the JSON and copy it to the clipboard.
- Start Visual Studio and add a new class to your project. Remove the supplied class so you are just left with the namespace and place the cursor between the brackets.
- From the Visual Studio Edit Menu select Paste Special and finally Paste JSON As Classes.
- Refactor the Class names as required.
The longer version
The first step is to obtain a copy of the JSON response. This could be via a an API client like Postman, your own app or the countless other alternatives.
If you have already obtained the JSON feel free to skip over this paragraph. I have built my own console app with a break point after the call to the webservice. Once the app reaches the breakpoint I can obtain the JSON from the locals windows. (a side note here is that that you will see the JSON has been wrapped in extra brackets so I will remove these before the next step.)
Copy the JSON to the clipboard.
Add a new C# class to your project. Delete the supplied class and place the cursor within the code editor.
From the Visual Studio Edit menu select Paste Special and finally Paste JSON As Classes.
The class(es) are now been created and the only change I will make will be to rename the top level class to something more meaningful.
I can now use them in my code.
Why not use VS Code?
A the time of writing I was using VS Code 1.42.1 which does not offer native support for Paste JSON as Classes.
The inspiration for this post came from this video by Bret Bentzinger.