4

我有以下内容:

var data = new List<DataModel>();

其中 DataModel 如下:

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

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

谢谢你,米格尔

4

1 回答 1

23

你可以用神奇的方式...

  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")
            };
    } 
于 2013-11-09T18:40:21.523 回答