微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 自定义集合属性未序列化

参见英文答案 > How do I get json.net to serialize members of a class deriving from List<T>?                                    2个
>             JSON serialize properties on class inheriting list                                     1个
我有一个自己的属性自定义集合.

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

当我使用PagedList< T>时在我的web api应用程序中,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)

解决方法

不完美,但您可以通过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; }
}

关键部分是公共IEnumerable< T>数据=> this.ToList();它仍然返回IEnumerable.我只试过这个,但这似乎不起作用(递归).那是因为我调用了ToList().

结果:

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

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

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐