a blog for those who code

Tuesday, 24 March 2015

Generating C# Classes from XML Or JSON

In this post we will discuss generating classes from XML or JSON. You can able to generate Classes from XML or JSON using Visual Studio. It is a real pain for the developers to create data type from the XML or from the JSON and there is a high possibility that you might miss something if the file is really big. This trick will come handy when you are taking XML or JSON feed from one system and you need to integrate it into your project.
Lets suppose we have a XML file as

<note_tree>
  <note>
    <to>To1</to>
    <from>From1</from>
    <heading>Reminder1</heading>
    <body>Do This1</body>
  </note>
  <note>
    <to>To2</to>
    <from>From2</from>
    <heading>Reminder2</heading>
    <body>Do This2</body>
    </note>
</note_tree>

When we paste this example in C# file as "Paste XML As Classes", it will create a set of classes that represents the XML data structure.

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

public partial class note_tree
{
   private note_treeNote[] noteField;
   /// <remarks/>
   [System.Xml.Serialization.XmlElementAttribute("note")]
   public note_treeNote[] note
   {
       get
       {
           return this.noteField;
        }
        set
        {
           this.noteField = value;
         }
     }
 }
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class note_treeNote
{
   private string toField;
   private string fromField;
   private string headingField;
   private string bodyField;
   /// <remarks/>
   public string to
   {
         get
         {
             return this.toField;
         }
         set
         {
             this.toField = value;
         }
    }

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

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

   /// <remarks/>
   public string body
   {
        get
        {
            return this.bodyField;
        }
        set
        {
            this.bodyField = value;
        }
    }
}
Similarly it will work for JSON documents as well when you will "Paste JSON As Classes".

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

CC License