ASP.NET Web API - Add Array Name to Exit

I am trying to change json output from web API. Say I have objects like People, the current output will look like this:

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

However, I would like the result to be as follows:

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

Any ideas on how to do this?

+5
source share
4 answers

Option 1 - Create a 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 - change JsonMediaTypeFormatter

You can still come back

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 a new formatter instead of the old JSON one:

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());
+14
source

Suppose the name of the variable is list name PersonList, which returns

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

.

       return new
        {
            people = PersonList
        };

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

DTO JSON. , .

public class ReturnedJson
{
   public IList<People> People {get;set;}
}

 public class People
{
   public string name {get;set;}
   public string sex{get;set;}
}

It is my assumption that you have a DTO for this json, because you have not shown any code.

0
source

Based on the second Filip W option, this draws nicely from the database, since List implements IEnumerable:

public dynamic Get () {

List<Person> personList = new List<Person>();

using (DataTable dt = db.ExecuteDataTable("PeopleSelect")) {
    foreach (DataRow dr in dt.Rows) {
        personList.Add(new Person { name = (string)dr["name"], ...});
    }
}

return new { people = personList };

}

0
source

All Articles