Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net Web API - Add Array Name to Output

I am trying to change the json output from the Web API. Say I have a objects like People, the current output would be like:

[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]

However I would like the output to be like:

{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}

Any Ideas on how this could be done?

like image 320
GrantC Avatar asked Jan 22 '13 04:01

GrantC


2 Answers

Option 1 - Create new model

Instead of returning

public IEnumerable<Person> Get()

return

public People Get()

where

public class People {
    public IEnumerable<Person> People {get; set;}
}

Option 2 - return dynamic

Instead of returning

public IEnumerable<Person> Get()

return

public dynamic Get() {
    IEnumerable<Person> p = //initialize to something;
    return new {people = p};
}

Option 3 - modify JsonMediaTypeFormatter

You can still return

public IEnumerable<Person> Get()

but add the following class:

public class PeopleAwareJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        if ((typeof (IEnumerable<People>).IsAssignableFrom(type)))
        {
            value = new {people = value};
        }
        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
    }
}

now in WebApiConfig just register the new formatter instead of old JSON one:

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());
like image 92
Filip W Avatar answered Nov 11 '22 08:11

Filip W


Lets assume variable name of list object is PersonList which returns

[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]

You can simply do returning as following without pain

       return new
        {
            people = PersonList
        };

then you'll have

{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}
like image 40
user3319247 Avatar answered Nov 11 '22 07:11

user3319247