C#, Code, Tips, Visual Studio

Visual Studio – Paste Special – JSON as Classes

This has been there since 2013 I believe, but I’m just now discovering it….wish I would have found it sooner as it’s an awesome feature.

Take a JSON (or XML as there is a Paste XML as Classes as well) like the following and copy it into the clipboard:

{
"People" :[{
    "First Name" : "Jason",
    "Last Name" : "Lautzenheiser", 
    "Address" : {
        "Street" : "1122 Main",
        "City" : "BigTown",
        "State" : "OH",
        "Zip" : 66554
    },
    "Phones" : [{
        "PhoneType" : "Home",
        "Number" : "330-555-7777"
      },
      {
        "PhoneType" : "Work",
        "Number" : "330-222-1111"
      }
    ]
  }]
}

Then under the Edit->Paste Special menu, there is an option for Paste JSON as Classes which will spit out the following code:

public class Rootobject
{
 public Person[] People { get; set; }
}

public class Person
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public Address Address { get; set; }
 public Phone[] Phones { get; set; }
}

public class Address
{
 public string Street { get; set; }
 public string City { get; set; }
 public string State { get; set; }
 public int Zip { get; set; }
}

What a beautiful thing that is. I recently had to import and manipulate some JSON data for a report which was much more complex than this. Within minutes I had my object model setup and the JSON files being read in.

Small feature, but what a time saver.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s