How To Paste JSON As Classes Or XML As Classes in Visual Studio

Introduction

In this article, I will show you a very interesting feature of Visual Studio. which is we can paste our JSON and XML as a class after copying that JSON or XML. In simple terms, if we have some JSON data or XML data and we want to generate classes for that data then Visual Studio has a feature for that. In that we will just copy the JSON data and when we paste the classes for JSON or XML it will be automatically generated.
 
Let us see how it is possible: 
 
Pasting JSON as Classes

Suppose I have the following JSON data:
  1. {  
  2.     "Employees": [  
  3.       {  
  4.         "userId""rirani",  
  5.         "jobTitleName""Developer",  
  6.         "firstName""Romin",  
  7.         "lastName""Irani",  
  8.         "preferredFullName""Romin Irani",  
  9.         "employeeCode""E1",  
  10.         "region""CA",  
  11.         "phoneNumber""408-1234567",  
  12.         "emailAddress""romin.k.irani@gmail.com"  
  13.     },  
  14.       {  
  15.         "userId""nirani",  
  16.         "jobTitleName""Developer",  
  17.         "firstName""Neil",  
  18.         "lastName""Irani",  
  19.         "preferredFullName""Neil Irani",  
  20.         "employeeCode""E2",  
  21.         "region""CA",  
  22.         "phoneNumber""408-1111111",  
  23.         "emailAddress""neilrirani@gmail.com"  
  24.     },  
  25.       {  
  26.         "userId""thanks",  
  27.         "jobTitleName""Program Directory",  
  28.         "firstName""Tom",  
  29.         "lastName""Hanks",  
  30.         "preferredFullName""Tom Hanks",  
  31.         "employeeCode""E3",  
  32.         "region""CA",  
  33.         "phoneNumber""408-2222222",  
  34.         "emailAddress""tomhanks@gmail.com"  
  35.     }]  
  36.   
How to generate classes for that in Visual Studio

Step 1:
Firstly, copy  above JSON Code and create a class file.

 
 
Step 2: Now select Code > Class. and give the name of the file. Then click on Add Button.

 
 
Step 3: Now remove your class code which is by default created by Visual Studio. Here's the screenshot,

 
 
Step 4: 

Now copy your JSON code. I am copying what I have written above. And click inside the namespace and Go to Edit > Paste Special and click on Paste JSON as Classes. Here's the figure:

 
 
Step 5: After clicking on that you will find your code is generated.

 
 
Pasting XML as Classes

Same likethe  above steps you can also paste XML as classes. To paste XML as classes go to Edit > Paste Special and click on Paste XML as Classes. Here's the figure,

 
 
Conclusion

In this article we have seen a new feature of Visual Studio and learned it, which is how we can generate classes for our JSON or XML code by copying and pasting in Visual Studio.
 
Read more articles on Visual Studio: