Recently i was writing a WCF Service which would be returning me result in JSON Format. I noticed I have to write this code everytime I have to convert the data into JSON strings.
How did I avoid repetetive task? By using extension Methods
The code I was using before discovering extension methodsĀ is given below
[OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] public string AccessPosRecords(int iPracticeId) { DLPmsMaster[] objPmsMaster = null; MSessionDetail objSessionDetail = SessionHandler.GetSessionObject(HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Session.SessionID); if (objSessionDetail != null) { objPmsMaster = objBPmsMaster.AccessPosRecords(iPracticeId); } //return objPmsMaster; JavaScriptSerializer oSerializer = new JavaScriptSerializer(); string sJSON = oSerializer.Serialize(objPmsMaster); return sJSON; }
The statements in bold are what needed to be repeated every time
The same thing can be done without repeating statements by using methods. Here is how to go about
First Create a Extension Class public static class JsonExtensions { public static string ToJson(this object obj) { JavaScriptSerializer serializer = new JavaScriptSerializer(); //Optional can use Var too. Var serializer = new JavaScriptSerializer(); return serializer.Serialize(obj); } OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] public string AccessPosRecords(int iPracticeId) { DLPmsMaster[] objPmsMaster = null; MSessionDetail objSessionDetail = SessionHandler.GetSessionObject(HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Session.SessionID); if (objSessionDetail != null) { objPmsMaster = objBPmsMaster.AccessPosRecords(iPracticeId); } return objPmsMaster.TOJson(); }
Required Namespace
using System.Web.Script.Serialization;
Reference Extension Methods
http://msdn.microsoft.com/en-us/library/bb311042.aspx