Advanced Ajapa Yoga Kriyas and Meditations for Software Developers : Tap the power of breath, mantra, mudra, and dhyana for improved focus, peace of mind, and blissful inner connection.


Convert JSON and XML markup into C# classes using Visual Studio

Visual Studio 2015 provides a plethora of features that make you more productive. One such feature that beginners often miss is converting XML or JSON markup into C# classes. This article discusses this feature with a few examples.

XML and JSON are the two commonly used data formats for serializing data over the wire. Many a times you need to map XML or JSON markup to C# classes. Suppose you are developing an application that consumes some Web API or WCF service. Further assume that the service returns data as XML or JSON. When this data is received in your application you would want to read the data and store in C# object(s). Thus you need C# classes that match the structure of the XML or JSON data. No doubt, you can create these C# classes manually but Visual Studio can provided a good starting point by automating the process.

If you open any C# code file - a file with .cs extension - you will find two menu options as shown below:

As you can see, the Edit menu contains Paste Special sub-menu with two options - Paste JSON As Classes and Paste XML As Classes. These two menu options do the respective class creation for you. Let's see how these options work with a few examples.

Create a new Console Application project in Visuals Studio and add an XML file and a JSON file to it using Add New Item dialog. These files are merely used to generate the sample XML and JSON markup. You can also create the markup in some external editor such as Notepad.

Now open the JSON file and enter the following markup in it:

{
  "employeeid": 1,
  "firstname": "Nancy",
  "lastname": "Davolio",
  "homephone": "(206) 555-9857"
}

Then copy the above markup using Ctrl + C and then switch to the Program.cs file.

Place your cursor below the Program class and then select Paste Special > Paste JSON As Classes menu option. This will generate a C# class as shown below:

public class Rootobject
{
    public int employeeid { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string homephone { get; set; }
}

As you can see, Rootobject class has been created for you with four public properties. The property names match the JSON key names. You can change the default class name and property names as per your needs,

Now, open the XML file and key-in the following markup:

<employee>
  <employeeid>1</employeeid>
  <firstname>Nancy</firstname>
  <lastname>Davolio</lastname>
  <homephone>(206) 555-9857</homephone>
</employee>

Repeat the above describe process, this time selecting Paste XML As Classes menu option. This will generate the following C# class:

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

    private byte employeeidField;

    private string firstnameField;

    private string lastnameField;

    private string homephoneField;

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

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

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

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

As you can see, the class generated from the XML markup is bit verbose and has XML serialization related attributes.

On. Now open the JSON file again and enter the following markup:

{
  "employees": [
    {
      "employeeid": 1,
      "firstname": "Nancy",
      "lastname": "Davolio",
      "homephone": "(206) 555-9857"
    },
    {
      "employeeid": 1,
      "firstname": "Andrew",
      "lastname": "Fuller",
      "homephone": "(206) 555-9482"
    },
    {
      "employeeid": 1,
      "firstname": "Janet",
      "lastname": "Leverling",
      "homephone": "(206) 555-3412"
    }
  ]
}

Now we have an array of objects in JSON format. If you copy-paste this array as before you will get this C# code:

public class Rootobject
{
    public Employee[] employees { get; set; }
}

public class Employee
{
    public int employeeid { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string homephone { get; set; }
}

Now the Rootobject clas contains an array of Employee objects. The Employee class defines the four public properties as before.

Let's repeat this with XML data.

<employees>
  <employee>
    <employeeid>1</employeeid>
    <firstname>Nancy</firstname>
    <lastname>Davolio</lastname>
    <homephone>(206) 555-9857</homephone>
  </employee>
  <employee>
    <employeeid>2</employeeid>
    <firstname>Andrew</firstname>
    <lastname>Fuller</lastname>
    <homephone>(206) 555-9482</homephone>
  </employee>
  <employee>
    <employeeid>3</employeeid>
    <firstname>Janet</firstname>
    <lastname>Leverling</lastname>
    <homephone>(206) 555-3412</homephone>
  </employee>
</employees>

This time the C# code generated will be as shown below:

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

    private employeesEmployee[] employeeField;

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

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

    private byte employeeidField;

    private string firstnameField;

    private string lastnameField;

    private string homephoneField;

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

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

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

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

Final example. Add the following JSON markup to the JSON file:

{
  "employeeid": 1,
  "firstname": "Nancy",
  "lastname": "Davolio",
  "phones": {
    "home": "(206) 555-9857",
    "work": "(206) 555-9482"
  }
}

This time it contains a nested phones object with two keys - home and work. Pasting this JSON into C# file will create the following code:

public class Rootobject
{
    public int employeeid { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public Phones phones { get; set; }
}

public class Phones
{
    public string home { get; set; }
    public string work { get; set; }
}

This time two classes get created - Rootobject and Phones. The Rootobject is as before whereas the Phones class contains the home and work properties.

Now enter the following XML markup that contains phones nested element:

<employee>
  <employeeid>1</employeeid>
  <firstname>Nancy</firstname>
  <lastname>Davolio</lastname>
  <phones>
    <home>(206) 555-9857</home>
    <work>(206) 555-9482</work>
  </phones>
</employee>  

Pasting the above XML markup will result in this C# code:

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

    private byte employeeidField;

    private string firstnameField;

    private string lastnameField;

    private employeePhones phonesField;

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

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

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

    /// <remarks/>
    public employeePhones phones
    {
        get
        {
            return this.phonesField;
        }
        set
        {
            this.phonesField = value;
        }
    }
}

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

    private string homeField;

    private string workField;

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

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

The code now has two classes - employee and employeePhones

The generated C# code may not be precisely as per your expectations. But you can always adjust and fine tune the class names and property names as per your application's need. Visual Studio does provide a good starting point helping you to save good amount of work.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Ajapa Japa and Shambhavi Mudra online course are available here.

Posted On : 29 November 2016







Advanced Ajapa Yoga Kriyas and Meditations for Software Developers : Tap the power of breath, mantra, mudra, and dhyana for improved focus, peace of mind, and blissful inner connection.