Visual Studio Feature: Convert JSON or XML to Classes

Introduction

In this article, I will demonstrate how to use the Visual Studio feature Paste JSON as Classes or XML as Classes. This feature was introduced in Visual Studio 2013. This compelling feature will help the developer convert JSON to a C# class or XML to a C# class. Before this, developers used to find online tools to convert JSON/XML to C# classes, but after the introduction of this feature in Visual Studio, it became easy for developers to create classes from JSON/XML without writing a single line of code. I have observed that many developers are not aware of this feature available in Visual Studio.

How to use the Visual Studio feature Paste JSON as Classes or XML as Classes?

Let's prepare JSON sample data.

{
   "Users": [
      {
         "UserId": "483c3ac3f38e84297c002546",
         "Email": "[email protected]",
         "Name": "[email protected]",
         "NickName": "test",
         "LoginsCount": 15,
         "Created_At": "2016-11-28T14:10:11.338Z",
         "Updated_At": "2016-12-02T01:17:29.310Z",
         "Last_Login": "2016-12-02T01:17:29.310Z",
         "Email_Verified": true
      },
      {
         "UserId": "583c5484cb79a5fe593425a9",
         "Email": "[email protected]",
         "Name": "[email protected]",
         "NickName": "test1",
         "LoginsCount": 1,
         "Created_At": "2016-11-28T16:00:04.209Z",
         "Updated_At": "2016-11-28T16:00:47.203Z",
         "Last_Login": "2016-11-28T16:00:47.203Z",
         "Email_Verified": true
      },
      {
         "UserId": "483c5484cb79a5fe593425b9",
         "Email": "[email protected]",
         "Name": "[email protected]",
         "NickName": "test1",
         "LoginsCount": 1,
         "Created_At": "2016-11-28T16:00:04.209Z",
         "Updated_At": "2016-11-28T16:00:47.203Z",
         "Last_Login": "2016-11-28T16:00:47.203Z",
         "Email_Verified": false
      },
      {
         "UserId": "383c5484cb79a5fe593423bD",
         "Email": "[email protected]",
         "Name": "[email protected]",
         "NickName": "test1",
         "LoginsCount": 1,
         "Created_At": "2016-11-28T16:00:04.209Z",
         "Updated_At": "2016-11-28T16:00:47.203Z",
         "Last_Login": "2016-11-28T16:00:47.203Z",
         "Email_Verified": false
      }
   ]
}

Open Visual Studio 2022 > Edit  > Paste special > paste JSON As classes.

pasteJsonToClass

Once JSON is copied and use above option then Visual Studio will take care of class creation for json data.

JSON Data

Now let's take a real-time example of when this feature is useful for developers. Let's take an example: you are starting a new requirement for the API endpoint for GetEmployees, which will return a JSON response, and you need to create classes manually for your JSON response. In that case, we can leverage this feature of Visual Studio to create classes from the JSON response.

Let's take a dummy sample rest pai example using this endpoint: https://dummy.restapiexample.com/api/v1/employees, which returns a list of employees in JSON format as below.

{
  "status": "success",
  "data": [
    {
      "id": 1,
      "employee_name": "Tiger Nixon",
      "employee_salary": 320800,
      "employee_age": 61,
      "profile_image": ""
    },
    {
      "id": 2,
      "employee_name": "Garrett Winters",
      "employee_salary": 170750,
      "employee_age": 63,
      "profile_image": ""
    },
    {
      "id": 3,
      "employee_name": "Ashton Cox",
      "employee_salary": 86000,
      "employee_age": 66,
      "profile_image": ""
    },
    {
      "id": 4,
      "employee_name": "Cedric Kelly",
      "employee_salary": 433060,
      "employee_age": 22,
      "profile_image": ""
    },
    {
      "id": 5,
      "employee_name": "Airi Satou",
      "employee_salary": 162700,
      "employee_age": 33,
      "profile_image": ""
    },
    {
      "id": 6,
      "employee_name": "Brielle Williamson",
      "employee_salary": 372000,
      "employee_age": 61,
      "profile_image": ""
    },
    {
      "id": 7,
      "employee_name": "Herrod Chandler",
      "employee_salary": 137500,
      "employee_age": 59,
      "profile_image": ""
    },
    {
      "id": 8,
      "employee_name": "Rhona Davidson",
      "employee_salary": 327900,
      "employee_age": 55,
      "profile_image": ""
    },
    {
      "id": 9,
      "employee_name": "Colleen Hurst",
      "employee_salary": 205500,
      "employee_age": 39,
      "profile_image": ""
    },
    {
      "id": 10,
      "employee_name": "Sonya Frost",
      "employee_salary": 103600,
      "employee_age": 23,
      "profile_image": ""
    },
    {
      "id": 11,
      "employee_name": "Jena Gaines",
      "employee_salary": 90560,
      "employee_age": 30,
      "profile_image": ""
    },
    {
      "id": 12,
      "employee_name": "Quinn Flynn",
      "employee_salary": 342000,
      "employee_age": 22,
      "profile_image": ""
    },
    {
      "id": 13,
      "employee_name": "Charde Marshall",
      "employee_salary": 470600,
      "employee_age": 36,
      "profile_image": ""
    },
    {
      "id": 14,
      "employee_name": "Haley Kennedy",
      "employee_salary": 313500,
      "employee_age": 43,
      "profile_image": ""
    },
    {
      "id": 15,
      "employee_name": "Tatyana Fitzpatrick",
      "employee_salary": 385750,
      "employee_age": 19,
      "profile_image": ""
    },
    {
      "id": 16,
      "employee_name": "Michael Silva",
      "employee_salary": 198500,
      "employee_age": 66,
      "profile_image": ""
    },
    {
      "id": 17,
      "employee_name": "Paul Byrd",
      "employee_salary": 725000,
      "employee_age": 64,
      "profile_image": ""
    },
    {
      "id": 18,
      "employee_name": "Gloria Little",
      "employee_salary": 237500,
      "employee_age": 59,
      "profile_image": ""
    },
    {
      "id": 19,
      "employee_name": "Bradley Greer",
      "employee_salary": 132000,
      "employee_age": 41,
      "profile_image": ""
    },
    {
      "id": 20,
      "employee_name": "Dai Rios",
      "employee_salary": 217500,
      "employee_age": 35,
      "profile_image": ""
    },
    {
      "id": 21,
      "employee_name": "Jenette Caldwell",
      "employee_salary": 345000,
      "employee_age": 30,
      "profile_image": ""
    },
    {
      "id": 22,
      "employee_name": "Yuri Berry",
      "employee_salary": 675000,
      "employee_age": 40,
      "profile_image": ""
    },
    {
      "id": 23,
      "employee_name": "Caesar Vance",
      "employee_salary": 106450,
      "employee_age": 21,
      "profile_image": ""
    },
    {
      "id": 24,
      "employee_name": "Doris Wilder",
      "employee_salary": 85600,
      "employee_age": 23,
      "profile_image": ""
    }
  ],
  "message": "Successfully! All records has been fetched."
}

Now I will use the paste JSON as classes feature to generate classes from the above response object.

Create a class file with no content as below.

Create class file

Now click on paste JSON as classes, which will generate classes for us.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonToClasses
{

    public class Rootobject
    {
        public string status { get; set; }
        public Datum[] data { get; set; }
        public string message { get; set; }
    }

    public class Datum
    {
        public int id { get; set; }
        public string employee_name { get; set; }
        public int employee_salary { get; set; }
        public int employee_age { get; set; }
        public string profile_image { get; set; }
    }

}

Now we can change the class name as per our coding standard or change the name according to requirements. Here I have changed my class name as per naming conventions and removed unused uses.

namespace JsonToClasses
{

    public class ResponseModel
    {
        public string status { get; set; }
        public List<Employee> data { get; set; }
        public string message { get; set; }
    }

    public class Employee
    {
        public int id { get; set; }
        public string employee_name { get; set; }
        public int employee_salary { get; set; }
        public int employee_age { get; set; }
        public string profile_image { get; set; }
    }

}

The same way we can do for XML data as well. Once XML data is copied and pasted as classes, the corresponding classes for the XML file will be generated.

  • Add a new class with the name XMLToClasses.
    Class
  • Remove the default class name and code from the class.
    XML
  • Let's convert the same JSON to XML.
    <?xml version="1.0" encoding="UTF-8" ?>
    <root>
    	<Users>
    		<UserId>483c3ac3f38e84297c002546</UserId>
    		<Email>[email protected]</Email>
    		<Name>[email protected]</Name>
    		<NickName>test</NickName>
    		<LoginsCount>15</LoginsCount>
    		<Created_At>2016-11-28T14:10:11.338Z</Created_At>
    		<Updated_At>2016-12-02T01:17:29.310Z</Updated_At>
    		<Last_Login>2016-12-02T01:17:29.310Z</Last_Login>
    		<Email_Verified>true</Email_Verified>
    	</Users>
    	<Users>
    		<UserId>583c5484cb79a5fe593425a9</UserId>
    		<Email>[email protected]</Email>
    		<Name>[email protected]</Name>
    		<NickName>test1</NickName>
    		<LoginsCount>1</LoginsCount>
    		<Created_At>2016-11-28T16:00:04.209Z</Created_At>
    		<Updated_At>2016-11-28T16:00:47.203Z</Updated_At>
    		<Last_Login>2016-11-28T16:00:47.203Z</Last_Login>
    		<Email_Verified>true</Email_Verified>
    	</Users>
    	<Users>
    		<UserId>483c5484cb79a5fe593425b9</UserId>
    		<Email>[email protected]</Email>
    		<Name>[email protected]</Name>
    		<NickName>test1</NickName>
    		<LoginsCount>1</LoginsCount>
    		<Created_At>2016-11-28T16:00:04.209Z</Created_At>
    		<Updated_At>2016-11-28T16:00:47.203Z</Updated_At>
    		<Last_Login>2016-11-28T16:00:47.203Z</Last_Login>
    		<Email_Verified>false</Email_Verified>
    	</Users>
    	<Users>
    		<UserId>383c5484cb79a5fe593423bD</UserId>
    		<Email>[email protected]</Email>
    		<Name>[email protected]</Name>
    		<NickName>test1</NickName>
    		<LoginsCount>1</LoginsCount>
    		<Created_At>2016-11-28T16:00:04.209Z</Created_At>
    		<Updated_At>2016-11-28T16:00:47.203Z</Updated_At>
    		<Last_Login>2016-11-28T16:00:47.203Z</Last_Login>
    		<Email_Verified>false</Email_Verified>
    	</Users>
    </root>
  • Copy XML File and use Paste Special > Paste XML As Classes.
    Paste

Once use the Paste XML As Classes option then that will generate the below class for us.

namespace XMLToClasse
{

    // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class root
    {

        private rootUsers[] usersField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute("Users")]
        public rootUsers[] Users
        {
            get
            {
                return this.usersField;
            }
            set
            {
                this.usersField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class rootUsers
    {

        private string userIdField;

        private string emailField;

        private string nameField;

        private string nickNameField;

        private byte loginsCountField;

        private System.DateTime created_AtField;

        private System.DateTime updated_AtField;

        private System.DateTime last_LoginField;

        private bool email_VerifiedField;

        /// <remarks/>
        public string UserId
        {
            get
            {
                return this.userIdField;
            }
            set
            {
                this.userIdField = value;
            }
        }

        /// <remarks/>
        public string Email
        {
            get
            {
                return this.emailField;
            }
            set
            {
                this.emailField = value;
            }
        }

        /// <remarks/>
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        public string NickName
        {
            get
            {
                return this.nickNameField;
            }
            set
            {
                this.nickNameField = value;
            }
        }

        /// <remarks/>
        public byte LoginsCount
        {
            get
            {
                return this.loginsCountField;
            }
            set
            {
                this.loginsCountField = value;
            }
        }

        /// <remarks/>
        public System.DateTime Created_At
        {
            get
            {
                return this.created_AtField;
            }
            set
            {
                this.created_AtField = value;
            }
        }

        /// <remarks/>
        public System.DateTime Updated_At
        {
            get
            {
                return this.updated_AtField;
            }
            set
            {
                this.updated_AtField = value;
            }
        }

        /// <remarks/>
        public System.DateTime Last_Login
        {
            get
            {
                return this.last_LoginField;
            }
            set
            {
                this.last_LoginField = value;
            }
        }

        /// <remarks/>
        public bool Email_Verified
        {
            get
            {
                return this.email_VerifiedField;
            }
            set
            {
                this.email_VerifiedField = value;
            }
        }
    }


}

Conclusion

In this article, we have learned how to use the Visual Studio feature. Paste JSON as classes or XML as classes, which will help the developer speed up their development and reduce manual work to write classes and each property of a class. By using this feature, we can generate classes from JSON or XML data by just copying and pasting in Visual Studio.

Thanks for reading. I hope this will help you boost your development.

If you wish to read my article on the Visual Studio feature, you can refer to the below articles.

  1. Create Documentation With Sandcastle Help Builder
  2. Tricks And Tips In Visual Studio To Speed Up Your Code Using Default Code Snippet Feature
  3. Boosting Your Productivity with .NET Core CLI Commands

Articles on .NET Core

  1. CRUD Operation With .NET Core 3.1 And Entity Framework Core
  2. Export Data In EXCEL, PDF, CSV, Word, JSON, XML and Text File In .NET Core 3.1 Using MVC Core
  3. CRUD Operation using Elastic Search And .Net Core API


Similar Articles