C#, Linq

Implementing ToJSON() Extension Method

In my previous post Extension Methods in .net 3.5, I have given basic idea and example of Extension methods.

What is JSON (JavaScript Object Notation)

JSON is a lightweight data-interchange format. It is easy for humans
to read and write. It is easy for machines to parse and generate.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is
    realized as an object, record, struct, dictionary, hash table, keyed
    list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

e.g.

{"StudentID":2,"Name":"Amol","School":"MIT"}

For more details see json.org , JSON in JavaScript and wikipedia

Implementing ToJSON() Extension Method

JavaScriptSerializer class provides Serialize method which Converts an object to a JSON string.

using System.Web.Script.Serialization; 
public static class JSONHelper
{
public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializerObj = new JavaScriptSerializer();
        return serializerObj.Serialize(obj);
    }
}

Uses

There is no difference between calling an extension method and the methods that are actually defined in a object.

See below example,

List stringList=new List();
        stringList.Add("Amol");
        stringList.Add("Jon");
      string jsonString= stringList.ToJSON();
// ToJSON method will return,
// ["Amol","Jon"]
 
Student studObj = new Student();
        studObj.Name = "Amol";
        studObj.School = "MIT";
        studObj.StudentID = 2;
        string jsonString= studObj.ToJSON();
// ToJSON method will return,
//{"StudentID":2,"Name":"Amol","School":"MIT"}

Leave a comment