MVC ApiController JSON objectroot

I am using Microsoft MVC 4 ApiController to render JSON for Ember app. ApiController returns JSON that looks like this:

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

Ember expects JSON to be formatted with objectroot like this:

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

The same applies to publishing a new customer record. Ember is a JSON message that has an object, and MVC expects JSON to be without an object:

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

I changed the WebApiConfig to change the JSON attributes to camelcase (so the keys look like "customerName" instead of "CustomerName"). I believe it is possible to add a JsonConverter to add / remove the JSON objectroot, but I cannot figure out how.

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);
        }
    }
}

      

+3


source to share


1 answer


Maybe you could do something like this, wrap your object in a parent object that has a clients property, although I haven't tested it:

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

      



Or, you can use a custom formatter like in this value:

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

+1


source







All Articles