Generate C# Classes from a JSON String Easily Using Visual Studio

As developers, we are often faced with certain tasks that are very repetitive in nature, which can also be time consuming to solve it. For example, whenever we need to reserialize a complex JSON string to classes we may need to write a lot of code. Until recently, whenever I needed to do such task I invariably create the classes manually and if it's a complex string, I was spending way too much time on that.

When the instances like these began to happen every now and then, I decided to search for online options which can spit out classes from a JSON string. After some googling, I found out this site json2csharp.com which can do what I was looking for. You only need to paste the JSON in the input box and click on the Generate button to get the classes in C#.

So, I began to follow this approach and was recommending it to my peers also. But things did change very recently, I was following up on a question in ASP.NET forums where a user asked for the same thing which I faced. From one of the answers posted in the thread I came to know that this feature is available out of the box in Visual Studio. At first, I thought that it's a new feature, but to my surprise I found out that it was even available from 2012. Truly a hidden gem.

You can access these feature from the menu Edit -> Paste Special -> Paste JSON as Classes

Please note that you may not see this by default. Copy JSON to clipboard, then check the menu to see the option.

I used the following JSON which generated the classes as shown below

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
public class Rootobject
{
    public Menu menu { get; set; }
}

public class Menu
{
    public string id { get; set; }
    public string value { get; set; }
    public Popup popup { get; set; }
}

public class Popup
{
    public Menuitem[] menuitem { get; set; }
}

public class Menuitem
{
    public string value { get; set; }
    public string onclick { get; set; }
}


No Comments

Add a Comment

Recent Posts