Friday, 13 May 2016

Custom JSON result class

Custom JSON result class that convert resopnse to JSON format in  Web API.

CustomJsonResult.cs


using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public class CustomJsonResult : JsonResult
{

    public string FormateStr { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (string.IsNullOrEmpty(this.ContentType))
        {
            response.ContentType = this.ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }

        if (this.ContentEncoding != null)
        {
            response.ContentEncoding = this.ContentEncoding;
        }

        if (this.Data != null)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string jsonString = jsSerializer.Serialize(Data);
            MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
            Regex reg = new Regex(@"\\/Date\((\d+)\)\\/");
            jsonString = reg.Replace(jsonString, matchEvaluator);
            response.Write(jsonString);
        }
    }

    private string ConvertJsonDateToDateString(Match m)
    {
        string result = string.Empty;
        DateTime dt = new DateTime(1970, 1, 1);
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)).ToLocalTime();
        return dt.ToString(FormateStr);
    }
}

How to use class in controllers ?


1.  return new CustomJsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };

2. return new CustomJsonResult
            {
                Data = data,
                JsonRequestBehavior = behavior,
                FormateStr = format
            };
3. return new CustomJsonResult
            {
                Data = data,
                FormateStr = format
            };
4. return new CustomJsonResult
            {
                Data = data,
                FormateStr = "yyyy-MM-dd HH:mm:ss"
            };

No comments:

Post a Comment

Parent-Child class declaration and initialization

using System; namespace CSharpDemo {     public class A     {         public void print()         {             Console.Wr...