beaudetious beaudetious - 3 months ago 13
JSON Question

Return camelCased JSON from Web API

I'm trying to return camel cased JSON from an ASP.Net Web API 2 controller. I created a new web application with just the ASP.Net MVC and Web API bits in it. I hijacked the ValuesController like so:

public class ValuesController : ApiController
{
public class Thing
{
public int Id { get; set; }
public string FirstName { get; set; }
public string ISBN { get; set; }
public DateTime ReleaseDate { get; set; }

public string[] Tags { get; set; }
}

// GET api/values
public IHttpActionResult Get()
{
var thing = new Thing
{
Id = 123,
FirstName = "Brian",
ISBN = "ABC213",
ReleaseDate = DateTime.Now,
Tags = new string[] { "A", "B", "C", "D"}
};

return Json(thing);
}
}


Running this in IE, I get the following results:

{"Id":123,"FirstName":"Brian","ISBN":"ABC213","ReleaseDate":"2014-10-20T16:26:33.6810554-04:00","Tags":["A","B","C","D"]}


Following K. Scott Allen's post on the subject, I added the following to the Register method in the WebApiConfig.cs file:

public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}


However, I still get the same, capitilization in my results. Is there something I'm missing? I've tried a few other approaches but nothing works yet.

Answer

Looks like the main issue was that I was using the JsonResult shortcut Json() action result method:

public IHttpActionResult Get([FromUri] string domain, [FromUri] string username)
{
    var authInfo = BLL.GetAuthenticationInfo(domain, username);
    return Json(authInfo);
}

It apparently had full control of formatting the results. If I switch to returning HttpResponseMessage then it works as expected:

public HttpResponseMessage Get([FromUri] string domain, [FromUri] string username)
{
    var authInfo = BLL.GetAuthenticationInfo(domain, username);
    return Request.CreateResponse(HttpStatusCode.OK, authInfo);
}

I did end up using the block of code in the WebApiConfig file as Omar.Alani suggested (opposed to the much lengthier code I had in my OP). But the real culprit was the JsonResult action method. I hope this helps someone else out.

Comments