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:
- {
- "Employees": [
- {
- "userId": "rirani",
- "jobTitleName": "Developer",
- "firstName": "Romin",
- "lastName": "Irani",
- "preferredFullName": "Romin Irani",
- "employeeCode": "E1",
- "region": "CA",
- "phoneNumber": "408-1234567",
- "emailAddress": "[email protected]"
- },
- {
- "userId": "nirani",
- "jobTitleName": "Developer",
- "firstName": "Neil",
- "lastName": "Irani",
- "preferredFullName": "Neil Irani",
- "employeeCode": "E2",
- "region": "CA",
- "phoneNumber": "408-1111111",
- "emailAddress": "[email protected]"
- },
- {
- "userId": "thanks",
- "jobTitleName": "Program Directory",
- "firstName": "Tom",
- "lastName": "Hanks",
- "preferredFullName": "Tom Hanks",
- "employeeCode": "E3",
- "region": "CA",
- "phoneNumber": "408-2222222",
- "emailAddress": "[email protected]"
- }]
- }
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: