Convert JSON to a C# Class

As a web developer, I regularly write code to consume and create data in a JSON format. It's a simple and easy way to represent data as a string and if you work with JSON every day, you'll know how much easier it is to use than XML.

Convert Json to C#

If you write most of your code in C# as I do, you may find that you are regularly creating C# class files manually. This can become tedious and often complex JSON structures can take some time to unwrap. However, there is a sneaky little trick that you can use in Visual Studio 2013 to automatically convert a JSON string to a C# class.

For example, let's take the JSON string below:

If you copy this string to your clipboard, and then navigate to Visual Studio, you can select Edit -> Paste Special -> Paste JSON as Classes.

Convert Json to C#

The string above will simply be converted into a C# class like the one below:

Easy right!? Well, almost......while Visual Studio does it's best to convert the JSON to a C# class, you may find that you need to slightly tweak the naming, but overall it converts really well. If you work with XML, the option to paste XML and convert to a C# class is also available. This new feature is a simple way to convert a JSON string to a C# class using the built in features in Visual Studio.

If you aren't able to upgrade to the latest version of Visual Studio, there is a handy online tool that you can use to get around this. Take a look at Using the online tool, you simply paste your JSON string and it will convert it online for you.

Happy deserializing!