Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List to JSon and return it in Web API action

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

like image 712
Miguel Moura Avatar asked Nov 29 '22 15:11

Miguel Moura


1 Answers

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")
            };
    } 
like image 92
Darrel Miller Avatar answered Dec 10 '22 18:12

Darrel Miller