将List转换为JSon并在Web API操作中返回它

时间:2013-11-09 17:43:58

标签: asp.net-web-api

我有以下内容:

var data = new List<DataModel>();

DataModel的位置如下:

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

如何将此List转换为JSON格式并在WebAPI 2.0操作中返回它?

谢谢你, 米格尔

1 个答案:

答案 0 :(得分:22)

你可以用神奇的方式做到这一点......

  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;
      }

  }

或者你可以做到“我想保持控制”

    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")
            };
    }