Thursday 25 October 2018

How to get CamelCase Json format in MVC 5 with System.Web.Mvc.JsonResult?

Well, I fall in a problem where all of my client side code like JavaScript was written with CamelCase format format to parse Web Api response. Every thing was working properly when Api was developed on DotnetCore with default Serializer Settings. After some time we have decided to downgrade the application on MVC 5 and now with System.Web.Mvc.JsonResult.Json() we are getting response with PascalCase format with default Serializer setting, and it broke all client side execution.

I tried to changed formatting with global setting on Application_Start with bellow code spinet

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;


That not worked for me, as i became able to know that Json() use in build JavaScriptSerializer to serialize object. The globally configured Serializer Settings will not affect with Json() .

So finally i decided to create my own helper that will help to change format.

public class JsonCamelCase : JsonResult
{
    private object _data;
    public JsonCamelCase(object data, JsonRequestBehavior jsonRequestBehavior = JsonRequestBehavior.DenyGet)
    {
        _data = data;
            base.JsonRequestBehavior = jsonRequestBehavior;
    }
 
 
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET"StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("GET verb not allowed for this operation, set JsonRequestBehavior to AllowGet.");
        }
 
        HttpResponseBase response = context.HttpContext.Response;
 
        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (_data != null)
        {
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
 
            response.Write(JsonConvert.SerializeObject(_data, Formatting.Indented, jsonSerializerSettings));
        }
    }
}

And in MVC controller instead of Json() i used JsonCamelCase(), it worked for me.
return new JsonCamelCase(questions);
//return Json(questions);