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.

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.

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 🙂

twittergoogle_plusredditpinteresttumblrmail

Written by Stephen Moon
email: stephen at logicalmoon.com
www: https://www.logicalmoon.com


Leave a Reply

Your email address will not be published. Required fields are marked *