Menu Home

Generate C# Classes from a JSON Response

The one sentence overview

Generate C# classes from a JSON response.

Why bother?

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

TL;DR

  1. Obtain the JSON and copy it to the clipboard.
  2. 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.
  3. From the Visual Studio Edit Menu select Paste Special and finally Paste JSON As Classes.
  4. 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.

Acknowledgements

The inspiration for this post came from this video by Bret Bentzinger.

Categories: C# JSON

oraclefrontovik

Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.