Convert JSON to a C# Class in Visual Studio

Introduction:

As a developer most of the time I depend on some online applications to convert my JSON data as a class(s), but this is not the case after exploring one of the cool paste special features in Visual Studio. In this blog you will learn, one of the features in Visual Studio which is used to convert the JSON as a Class using paste special option, where most of the developers are not aware of it.

There is one more use case where it will be really helpful when you need to create a class based on the API response and you’re getting JSON data.

Paste JSON as a Classes:

Open your solution in Visual Studio.

Copy the JSON object for which you need to create a class. 

Assume I had copied the below JSON Object. 

{
  "employee": {
    "name": "Ramu",
    "salary": 100000,
    "married": false
  }
}

Then go to Edit->Paste Special->Paste JSON as Object, as shown in the below figure.

Figure 1: Paste Special
  public class Rootobject
    {
        public Employee employee { get; set; }
    }

    public class Employee
    {
        public string name { get; set; }
        public int salary { get; set; }
        public bool married { get; set; }
    }

From the above code you can observe the JSON data is converted to C# Class.

This will also work for s complex JSON object.

{
  "employee": {
    "name": "Ramu",
    "salary": 100000,
    "married": false,
    "department": {
      "text": "nSure",
      "value": 1
    }
  }

After applying Paste Special.

   public class Rootobject
    {
        public Employee employee { get; set; }
    }

    public class Employee
    {
        public string name { get; set; }
        public int salary { get; set; }
        public bool married { get; set; }
        public Department department { get; set; }
    }

    public class Department
    {
        public string text { get; set; }
        public int value { get; set; }
    }
Summary:

Convert JSON to Class using paste special is one of my favorite features in Visual Studio, where most of the developers are not aware of this. We have seen how it will be really handy when you want to convert the complete JSON object into a class. You can also paste the XML as classes as we did it for JSON as classes.

gowthamk91

Leave a Reply

Discover more from Gowtham K

Subscribe now to keep reading and get access to the full archive.

Continue reading