ASP.NET – JSON – Serialization and Deserialization

I was looking around for a simple example which would just do a object serialization to a JSON format, and then deserializing back to the original object. I found few examples on MSDN, but did seem to be too long to try. Here I’ve given a simple code which would make your understanding easy, and simpler.

Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.

What is JSON?

JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.

Okay, I understood a little about JSON. Give me an example!

I know an example will get your understanding much better. Below is a simple example of how an object can be expressed in JSON notation. Let’s take a classical example of a Person object, and expressing myself as an object.

{
   “firstName”: “Rakki”,
   “lastName”:”Muthukumar”,
   “department”:”Microsoft PSS”,
   “address”: {
      “addressline1”: “Microsoft India GTSC”,
      “addressline2”: “PSS - DSI”,
      “city”: “Bangalore”,
      “state”: “Karnataka”,
      “country”: “India”,
      “pin”: 560028
   }
   “technologies”: [“IIS”, “ASP.NET”,“JavaScript”,“AJAX”]
}

In the above example, address is another object inside my Person, and technologies is an array or strings.

Express this as a simple .NET class, please!

Here is a simple example:

public class Address
{
    public string addressline1, addressline2, city, state, country;
    public int pin;
}

public class Person
{
    public string firstName, lastName, department;
    public Address address = new Address();
    public string[] technologies;
}

I get it. Now what? JSON Serialization / Deserialization?

I’m sure you do not want me to write what is serialization, and deserialization here. I’ll touch upon how to use System.Web.Script.Serialization.JavaScriptSerializer to convert an existing object into a JSON string.

JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Rakki";
p1.lastName = "Muthukumar";
p1.department = "Microsoft PSS";
p1.address.addressline1 = "Microsoft India GTSC";
p1.address.addressline2 = "PSS - DSI";
p1.address.city = "Bangalore";
p1.address.state = "Karnataka";
p1.address.country = "India";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

string str = js.Serialize(p1);

Above code just creates a Person object, and assign some values. Look at the last line where we are actually doing a serialization – means dumping the contents of the object to a JSON notation. Below is the string produced by the above code:

{"firstName":"Rakki","lastName":"Muthukumar","department":"Microsoft PSS","address":{"addressline1":"Microsoft India GTSC","addressline2":"PSS - DSI","city":"Bangalore","state":"Karnataka","country":"India","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}

It is the same as how we defined the object before – but in a single line. Now, you have successfully converted your object into a JSON string.

Now how do I deserialize it?

Before going into how to deserialize it, let’s just understand when you might want to deserialize the object. Classical example is a JSON object returned from a web service, or from your client side javascript code, and you will be able to deserialize it in the server side to use the received object.

Person p2 = js.Deserialize(str);
Response.Write(p2.lastName);

p2.lastName would contain “Muthukumar” if your deserialization works fine. I suggest you to use the Deserialize method since it will reduce the type casting you might be doing if you use DeserializeObject() method which returns a System.Object.


Originally Posted: http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx
By Rakki Muthukumar – Last Edited: 30 Jan 2009

Adding groups to the ASP.NET DropDownList control

Introduction

The ASP.NET DropDownList class doesn’t support option groups. (Presumably because it would break the ListItem paradigm that Microsoft has used for all their list orientated controls).

A grouped drop down list

However, it is possible to add basic option group functionality by inheriting from DropDownList and overriding the RenderContents() method. This technique for adding optgroups is fully compatible with ViewState.

Code

public class DropDownListX : DropDownList
{
    public void AddItemGroup(string groupTitle)
    {
        this.Items.Add(new ListItem(groupTitle, "$$OPTGROUP$$OPTGROUP$$"));
    }

    protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
    {
        if (this.Items.Count > 0)
        {
            bool selected = false;
            bool optGroupStarted = false;
            for (int i = 0; i < this.Items.Count; i++)
            {
                ListItem item = this.Items[i];
                if (item.Enabled)
                {
                    if (item.Value == "$$OPTGROUP$$OPTGROUP$$")
                    {
                        if (optGroupStarted)
                            writer.WriteEndTag("optgroup");
                        writer.WriteBeginTag("optgroup");
                        writer.WriteAttribute("label", item.Text);
                        writer.Write('>');
                        writer.WriteLine();
                        optGroupStarted = true;
                    }
                    else
                    {
                        writer.WriteBeginTag("option");
                        if (item.Selected)
                        {
                            if (selected)
                            {
                                this.VerifyMultiSelect();
                            }
                            selected = true;
                            writer.WriteAttribute("selected", "selected");
                        }
                        writer.WriteAttribute("value", item.Value, true);
                        if (item.Attributes.Count > 0)
                        {
                            item.Attributes.Render(writer);
                        }
                        if (this.Page != null)
                        {
                            this.Page.ClientScript.RegisterForEventValidation(
                                this.UniqueID, 
                                item.Value);
                        }
                        writer.Write('>');
                        HttpUtility.HtmlEncode(item.Text, writer);
                        writer.WriteEndTag("option");
                        writer.WriteLine();
                    }
                }
            }

            if (optGroupStarted)
            {
                writer.WriteEndTag("optgroup");
            }
        }
    }
}

Usage

To add the class to your project, simply copy and paste the code into a class file.

You will probably need to add the following line to the section of your web.config. The line gives ASP.NET another namespace to search when it’s resolving the controls in your pages. The namespace needs to match the one that you used for your DropDownListX class.

<add tagPrefix="asp" namespace="YourNameSpace.Goes.Here" />

Once that’s been done you can use the control directly within an ASPX page. The control will operate exactly like a normal DropDownList, except that you can also add groups to it.

<asp:DropDownListX ID="ddlxSomething" runat="server" />

To add grouped items to the control you will need to use the inherited Items.Add() method and our new AddItemGroup() method. (Databinding will still work but then you don’t have an easy way of adding the groups).

this.ddlx.AddItemGroup("Administrators");
foreach(User u in administrators)
{
    this.ddlx.Items.Add(u.Name, u.Id);
}

this.ddlx.AddItemGroup("Users");
foreach(User u in users)
{
    this.ddlx.Items.Add(u.Name, u.Id);
}

Caveats

You can’t add an item with a value that matches the special group value: $$OPTGROUP$$OPTGROUP$$. Of course, if the group value isn’t “unusual” enough you can always change it.


This Article was taken from: http://ignatu.co.uk/articles/Adding_groups_to_the_ASPNET_DropDownList_control/
Last modified: 26 June 2011.

The code is based on this code by Jeff Putz.

The Perfect Server – Ubuntu 10.04 [ISPConfig 3]

In order to begin my development career and have a platform from which to publish to the web, I decided that I wanted my own server. I’m not talking about a paid web hosting plan, I mean renting an actual physical machine, from which I can configure to publish my works, and to use as a development server. This tutorial sets out step by step how this can be achieved using a machine running Ubuntu 10.04.

http://www.howtoforge.com/perfect-server-ubuntu-10.04-lucid-lynx-ispconfig-3

Author: Falko Timme

 

I found this tutorial extremely informative and useful for configuring my server, and I hope it helps you to do the same thing!