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?
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());
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"}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With