4

I have the following:

var data = new List<DataModel>();

Where DataModel is the following:

public class DataModel {
  public DateTime Date { get; set; }
  public Int32 Users { get; set; }
}

How turn this List into a JSON forma and return it in a WebAPI 2.0 action?

Thank you, Miguel

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

23

You can do it the magic way...

  public class JsonListObjectController : ApiController
  {
      public List<DataModel> Get()
      {
          var data = new List<DataModel>()
        {
            new DataModel() {Date = DateTime.Today, Users = 100},
            new DataModel() {Date = DateTime.Today, Users = 120}
        };

          return data;
      }

  }

or you can do it the "I want to stay in control way"

    public HttpResponseMessage Get()
    {
        var data = new List<DataModel>()
        {
            new DataModel() {Date = DateTime.Today, Users = 100},
            new DataModel() {Date = DateTime.Today, Users = 120}
        };

        return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(data).ToString(), Encoding.UTF8, "application/json")
            };
    } 
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • 1
    Working with Web API for the first time I ran into this issue and your answer helped me. Chrome did however confuse me with its XML response instead of JSON to which this link will give more info to anyone who hits the same issue: http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome – KDT Feb 12 '15 at 07:18
  • 2
    @KDT You will learn quickly that making requests directly from the browser to test APIs will bring you lots of pain. Use a tool designed for the job like fiddler, postman, runscope, devHttpClient, etc – Darrel Miller Feb 12 '15 at 15:01