Cool Visual Studio 2017 Tip #1 : Creating JSON Classes Automatically

Visual Studio is pretty cool and there are a whole heap of in-built tools that can save you precious time. Here’s one of them: creating classes from JSON automatically.

Let’s imagine you have some JSON floating around that you need to process using .NET through something like Newtonsoft’s Json.NET. You could of course create them by hand, but that’s not necessary because Visual Studio has (for some time) allowed you to automatically create them with a simple paste command. Let’s start with our JSON.

1
2
3
4
5
6
{
"name":"Stephen",
"address":"London",
"numbers":["100","200","300"],
"animal":{"pet":"dog"}
}

As you can see, we have my name (in case I forget it), my address to the nearest city, a bunch of numbers stored as an array, and another object called animal which has one property: pet. No real surprises there other than what I would do with that :-) We’ll need a project next, so let’s begin with some menu items.

  • File > New Project.
  • Choose Templates > Visual C# > Windows Classic Desktop > Console App (.NET Framework).
  • Click OK.

Basic project set up: tick. How about somewhere to store our new classes in?

  • Project > Add Class.
  • Type: JSONClasses.
  • Click Add.

Looking good so far, but we don’t need the basic stuff inserted for us.

  • Remove: class JSONClasses { }

Now for the magic. We’re going to add in our auto-generated classes based on the JSON.

  • Edit > Paste Special… > Paste JSON as Classes.
  • All those lovely classes appear from the ether.
  • Lastly, remove a couple of blank lines to tidy it all up, and we’re all done.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace ConsoleApp1
{
public class Rootobject
{
public string name { get; set; }
public string address { get; set; }
public string[] numbers { get; set; }
public Animal animal { get; set; }
}

public class Animal
{
public string pet { get; set; }
}
}

So what choices did Visual Studio make? Well, name and address we’re strings, but that was fairly obvious. The numbers are also strings, but again, that is what we stated in the JSON. You can also see that all the properties match the names given in the JSON. The Animal object is a little interesting. It created a getter/setter for us and a new object reference and definition with its own string (see lines 8 and 13). One last thing is the main class: Rootobject. You might want to select something a little more descriptive :-)


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com