Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Simple JSON Handler for ASP.NET 2.0 to Implement AJAX Functionality

, 1 Jul 2011 CPOL
Simple JSON handler for ASP.NET 2.0 to implement AJAX functionality
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Reflection;
using System.Web.SessionState;

namespace SampleJSONWeb
{
    public abstract class JsonRequestHandler : IHttpHandler, IRequiresSessionState
    {

        public abstract void ProcessRequest(HttpContext context);

        protected void SetResponse(HttpContext context, string jsonResponse)
        {
            context.Response.Cache.SetExpires(DateTime.Now);
            context.Response.ContentType = "application/json";
            context.Response.Write(jsonResponse);
            context.Response.End();
        }

        protected void SetResponse(HttpContext context, Dictionary<string, string> attributes)
        {
            SetResponse(context, GetJsonObject(attributes));
        }

        protected void SetResponse<T>(HttpContext context, T obj)
        {
            SetResponse(context, GetJsonObject<T>(obj));
        }

        protected T CreateObjectFromRequest<T>(HttpContext context) where T: new()
        {
            T ob = new T();
            PropertyInfo[] properties = typeof(T).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                string value = context.Request.Params[property.Name];
                if (value == null)
                {
                    continue;
                }

                if (property.PropertyType != typeof(string) && value == string.Empty)
                {
                    continue;
                }

                object convertedValue = Convert.ChangeType(value, property.PropertyType);
                if (convertedValue == null)
                {
                    continue;
                }

                property.SetValue(ob, convertedValue, null);
            }
            return ob;
        }

        protected string GetJsonObject(Dictionary<string, string> attributes)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{");
            bool firstTime = true;
            foreach (string key in attributes.Keys)
            {
                if (!firstTime)
                {
                    jsonBuilder.Append(",");
                }

                string name = key;
                object value = attributes[key];
                jsonBuilder.Append("\"" + name + "\":" + value.ToString());
                firstTime = false;
            }
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        protected string GetJsonCollection<T>(IEnumerable<T> collection)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");

            bool first = true;
            foreach (T item in collection)
            {
                if (!first)
                {
                    jsonBuilder.Append(",");
                }
                jsonBuilder.Append(GetJsonObject<T>(item));
                first = false;
            }

            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }

        protected string GetJsonObject<T>(T obj)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{");
            bool firstTime = true;
            foreach (PropertyInfo property in properties)
            {
                if (!firstTime)
                {
                    jsonBuilder.Append(",");
                }

                string name = property.Name;
                object value = property.GetValue(obj, null);
                jsonBuilder.Append("\"" + name + "\":\"" + value.ToString() + "\"");
                firstTime = false;
            }
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pubudu Kasakara
Architect
Singapore Singapore
Pubudu Kasakara is working as Solution Architect in Singapore. He has more than 11 years of professional involvement in the IT industry. Worked in successful projects involving mainly the Service Oriented Application by contributing to all requirements gathering, design and implementation phases. He is having experience with SOA applications development, Microsoft .NET, BizTalk, He is member of Charted It professional in UK.
 
Solution Architect
http://www.kasakara.com

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 1 Jul 2011
Article Copyright 2011 by Pubudu Kasakara
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid