Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ApiController JSON objectroot

I'm using Microsoft MVC 4 ApiController to render JSON for an Ember application. The ApiController returns JSON, which looks like:

[{"id": 1, "customerName": "Customer 1"}]

Ember expects the JSON to be formatted with an objectroot like this:

{"customers": [{"id": 1, "customerName": "Customer 1"}]

The same goes for posting a new Customer record. Ember posts JSON, which has the objectroot, while MVC expects the JSON to be without the objectroot:

{"customers": [{"customerName": "Customer 1"}]

I've changed the WebApiConfig to change JSON attributes to camelcase (so the keys looks like "customerName" instead of "CustomerName"). I believe it's possible to add a JsonConverter to add / remove the JSON objectroot, but I can't figure out how to do it.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

The controller looks like this:

public class CustomersController : ApiController
{
    private DatabaseContext db = new DatabaseContext();

    public IEnumerable<Customer> GetCustomers()
    {
        return db.Customers.AsEnumerable();
    }

    public HttpResponseMessage PostCustomer([FromBody] Customer customer)
    {
        if (ModelState.IsValid)
        {
            db.Customers.Add(customer);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = customer.Id }));
            return response;
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
}
like image 442
Martin Avatar asked Nov 23 '25 20:11

Martin


1 Answers

You could probably do something like this, wrap your object in a parent object that has a customers property, though I haven't tested it:

var mycust = new { customers = customer };
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, mycust);

Or you can use a custom formatter, as in this gist:

https://gist.github.com/eed3si9n/4554127

like image 134
Erik Funkenbusch Avatar answered Nov 26 '25 12:11

Erik Funkenbusch