mercredi 26 août 2015

ASP.NET Web API - Configure the JSON response to conform to JSON API

Version 1 of my ASP.NET Web API for Ember.js was producing JSON that looked like this:

     [{"id":1,"name":"House of Crap","category":"Retail","street_name":"Washington Street"},
     {"id":2,"name":"Sketchy Automotive","category":"Automotive","street_name":"4th Street"},
     {"id":3,"name":"Toxins Are Us","category":"Chemical","street_name":"Highway 93"},
     {"id":4,"name":"Tricky Restaurant","category":"Restaurant","street_name":"4th Street"}]

I need something that looks like this:

     {"property":
     [{"id":1,"name":"House of Crap","category":"Retail","street_name":"Washington Street"},
     {"id":2,"name":"Sketchy Automotive","category":"Automotive","street_name":"4th Street"},
     {"id":3,"name":"Toxins Are Us","category":"Chemical","street_name":"Highway 93"},
     {"id":4,"name":"Tricky Restaurant","category":"Restaurant","street_name":"4th Street"}]}

One of my subs accomplished this as follows: He created a simple view-model class.

    namespace EnvironWeb.ViewModels
    {
        public class PropertyVM
        {
            public IEnumerable<property> property { get; set; }
        }
    }

He then made the GetProperties controller method of the type of the new class.

    public PropertyVM GetProperties()
    {
        var model = new PropertyVM();
        model.property = repository.GetAll();

        return model;
    }

It's clever, but is it the best approach? The JsonConverter looks promising, but I'm not sure I can accomplish it with the JsonConverter.




Aucun commentaire:

Enregistrer un commentaire