自定义集合属性未序列化

时间:2017-10-26 12:41:24

标签: c# asp.net-web-api serialization json.net

我有一个拥有自己属性的自定义集合。

 public interface IPagedList<T>: IList<T>
 {
     int TotalCount { get; }
 }

我有一个实现IPagedList接口的课程。

 public class PagedList<T> : List<T>, IPagedList<T>
 {
        public PagedList(IQueryable<T> source){
        AddRange(source);
        }

    public int TotalCount { get; private set; }
 }

当我在web api应用程序中使用PagedList<T>类时,TotalCount属性未序列化。

public class EmpolyeeController : ApiController
{
    public IHttpActionResult Get()
    {
        IPagedList<Employee> response = new PagedList<Employee>(Database.GetEmplyees());

        return Ok(response);
    }

}

响应是这样的:

[
    {
        "Id": "1230a373-af54-4960-951e-143e75313b25",
        "Name": "Deric"
    }
]

但我希望在json响应中看到TotalCount属性。

enter image description here

您可以在截屏视频中看到Raw View中的属性。

(我认为这是json.net的IList序列化问题的原始视图。如何添加中间件Raw View serailization)

1 个答案:

答案 0 :(得分:0)

不完美,但您可以通过JsonObject属性

将其视为对象
[JsonObject]
public class PagedList<T> : List<T>, IPagedList<T>
{
    public PagedList(IQueryable<T> source)
    {
        AddRange(source);
    }

    public IEnumerable<T> Data => this.ToList();

    public int TotalCount { get; private set; }
}

关键部分是public IEnumerable<T> Data => this.ToList();仍然返回IEnumerable。我只尝试this,但这似乎不起作用(递归)。那是因为我打电话给ToList()

结果:

{
    "Data": [
        {
            "Foo": "Foo",
            "Bar": "Bar"
        }
    ],
    "TotalCount": 0,
    "Capacity": 4,
    "Count": 1
}

作为替代方案,您可以使用自定义JsonConverter

您还应该问问自己,为什么在第一种情况下需要扩展List?

imho更好的方法是将您的数据转移到特定的响应模型中:

MyResponseModel<T>
{
     public int TotalCount { get; set; }
     public IEnumerable<T> Data { get; set; }
}

然后服务应该负责提供它。

相关问题