Convert xml, json to class in asp.net c# by one click

Convert XML or JSON into a class by using visual studio is as easy as just copy and two clicks, never matter how big or how complicated is our XML or JSON. In this article we will create some dummy XML and json and will try to convert them into class without writing a single property manually. It does not create 100% correct data type but created all the properties for. Say we have an XML or JSON with node Zipcode with value 11011, when we will create class it will create the property Zipcode with data type string, which is correct, because we cannot say what data type it is, whether string or integer so how the system can decide it. But after modifying with our desired data type it will be useable.

First we will try to create a class from a very simple xml then a complicated one so let’s try to create class from this customer XML

<Customers>
  <Customer>
    <CustomerID>123</CustomerID>
    <CompanyName>Great Lakes Food Market</CompanyName>
    <ContactName>Howard Snyder</ContactName>
    <ContactTitle>Marketing Manager</ContactTitle>
    <Phone>(503) 555-7555</Phone>
  </Customer>
  <Customer>
    <CustomerID>124</CustomerID>
    <CompanyName>Hungry Coyote Import Store</CompanyName>
    <ContactName>Yoshi Latimer</ContactName>
    <ContactTitle>Sales Representative</ContactTitle>
    <Phone>(503) 555-6874</Phone>
    <Fax>(503) 555-2376</Fax>
  </Customer>
</Customers>

First create a class file say “Customer.cs” and removed all the code from it, removing the code is not necessary, if we want to create the class in some existing class even then we can use this technique, enough talked let’s create a class from our above XML.

  1. Copy one customer record i.e. <customer> to </customer>
  2. Open the customer.cs file and put the cursor where you want to create the class
  3. From Menu click Edit => Paste Special => Paste XML as Classes
  4. Our class is created

Here is our created class

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Customer
{

    private byte customerIDField;

    private string companyNameField;

    private string contactNameField;

    private string contactTitleField;

    private string phoneField;

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

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

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

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

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

If you can notice the very first property public byte CustomerID, its data type is byte while we expect it an integer so these would be only small changes otherwise it is good to use in our application, it’s really quick and time saver. Now we will move the customer id as attribute of customer node and add the Address node to every customer and our XML will look like this

<Customer CustomerID=”123”>
      <CompanyName>Great Lakes Food Market</CompanyName>
      <ContactName>Howard Snyder</ContactName>
      <ContactTitle>Marketing Manager</ContactTitle>
      <Phone>(503) 555-7555</Phone>
      <FullAddress>
        <Address>2732 Baker Blvd.</Address>
        <City>Eugene</City>
        <Region>OR</Region>
        <PostalCode>97403</PostalCode>
        <Country>USA</Country>
      </FullAddress>
 </Customer>

According to it, we need two classes one is customer and other is FullAddress which will be used as a property in customer class, will it be done by paste special, let’s try by copying above XML. It did the same as we expected here is the result (I removed some properties for clarity)

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Customer
{
    .........................................

    private CustomerFullAddress fullAddressField;

    .........................................

    /// <remarks/>
    public CustomerFullAddress FullAddress
    {
        get
        {
            return this.fullAddressField;
        }
        set
        {
            this.fullAddressField = value;
        }
    }

}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class CustomerFullAddress
{

    private string addressField;

    private string cityField;

    private string regionField;

    private uint postalCodeField;

    private string countryField;

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

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

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

    /// <remarks/>
    public uint PostalCode
    {
        get
        {
            return this.postalCodeField;
        }
        set
        {
            this.postalCodeField = value;
        }
    }

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

JSON: Luckily I have the json of same XML so we can try to convert them into class by just change in one step in place of Paste XML as Classes to Paste JSON as Classes, and here is our first json

{ 
    "Customer": 
      {
        "CustomerID": "123",
        "CompanyName": "Great Lakes Food Market",
        "ContactName": "Howard Snyder",
        "ContactTitle": "Marketing Manager",
        "Phone": "(503) 555-7555"
      }
}

Copy it and try Paste JSON as Classes and it will create a very compact class, here is the result

public class Rootobject
{
    public Customer Customer { get; set; }
}

public class Customer
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }
    public string Phone { get; set; }
}

Note it created every property as string and used auto getter setter and one more class Rootobject which is not needed so you can delete it. So our final complicated json

{
  "Customer": {
    "CustomerID": "123",
    "CompanyName": "Great Lakes Food Market",
    "ContactName": "Howard Snyder",
    "ContactTitle": "Marketing Manager",
    "Phone": "(503) 555-7555",
    "FullAddress": {
      "Address": "2732 Baker Blvd.",
      "City": "Eugene",
      "Region": "OR",
      "PostalCode": "97403",
      "Country": "USA"
    }
  }
}

And here is the final classes generated by Visual Studio

public class Customer
{
    public string CustomerID { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }
    public string Phone { get; set; }
    public Fulladdress FullAddress { get; set; }
}

public class Fulladdress
{
    public string Address { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
}
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • xml
  • json
  • c#
  • object
  • asp.net
By Ali Adravi On 20 Dec, 14  Viewed: 735

Other blogs you may like

Read write xml in asp.net c#

Reading and writing in xml can be done in different ways, some common classes people use are XmlTextReader, XmlTextWriter , XmlDocument but we will use XDocument. By using the other classes say XmlTextReader we need to use the while loop to read and check every node by using XmlNodeType, for a long... By Ali Adravi   On 20 Dec 2014  Viewed: 1,766

XmlDocument Vs XDocument and their usage

When there was XmlDocument why we need XDocument, is there any better feature available with XDocument, answer is yes, XDocument has a number of benefits, easy to create, easy to update, easy to search, ability to use LINQ to XML, cleaner object model etc. In this post we will see some examples... By Ali Adravi   On 16 Mar 2013  Viewed: 1,075

HTML vs XHTML

HTML syntax, this is the format suggested for most authors. It is compatible with most legacy Web browsers. If a document is transmitted with the `text/html MIME` type, then it will be processed as an HTML document by Web browsers. This specification defines version 5 of the HTML syntax, known as... By Alicia Gonzalez   On 25 Dec 2012  Viewed: 421

What is XML and it's usage?

XML (Extensible Markup Language) is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. It was derived from an older standard format called SGML. **XML Used For** XML is one of the most widely-used... By Alicia Gonzalez   On 25 Dec 2012  Viewed: 296

Use XSLT to create menu from database

In some situations we need to create website menu from database, say our application have ability to create pages so that must also need to have a menu item to go to that page. So how to create menu with all those nice CSS and other settings, I think XSLT is best to use in these... By Hamden   On 16 Mar 2013  Viewed: 791