PagedList< T>的Newtonsoft.Json序列化.不包括某些属性 [英] Newtonsoft.Json serialization of PagedList<T> is not including some properties
问题描述
我正在尝试序列化PagedList对象( https://github.com/martijnboland/MvcPaging/blob/master/src/MvcPaging/PagedList.cs )发送给Json,就像这样:
I am trying to serialize a PagedList object ( https://github.com/martijnboland/MvcPaging/blob/master/src/MvcPaging/PagedList.cs ) to Json, like this:
PagedList<Product> pagedList = new PagedList<Product>(products, (page - 1), pageSize);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(pagedList);
如果使用上面的代码,结果将得到正确序列化的Product对象数组.但是,(PagedList的)以下属性未包含在Json结果中:
If I use the above code, in the result I get an array of Product objects serialized properly. However the properties below (of PagedList) are not being included in the Json result:
public bool HasNextPage { get; }
public bool HasPreviousPage { get; }
public bool IsFirstPage { get; }
public bool IsLastPage { get; }
public int ItemEnd { get; }
public int ItemStart { get; }
public int PageCount { get; }
public int PageIndex { get; }
public int PageNumber { get; }
public int PageSize { get; }
public int TotalItemCount { get; }
它们没有被序列化,但是它们是PagedList的一部分.
They are not being serialized but they are part of PagedList.
有人知道为什么吗?以及如何在序列化中包含这些属性?
Does anyone know why? And how could I include those properties in the serialization?
谢谢
推荐答案
序列化程序发现PagedList是可枚举的,因此将其序列化为JavaScript数组.为了使其更易于处理,我在PagedList对象上公开了一个GetMetaData()
函数,该函数将返回一个MetaData对象,该对象完全包含您上面提到的字段.这意味着您可以像这样序列化您的页面列表:
The serializer sees that PagedList is enumerable, so it serializes it to a JavaScript array. To make this easier to deal with I expose a GetMetaData()
function on the PagedList object that will return a MetaData object containing exactly the fields you mentioned above. This means you can serialize your pagedlist like so:
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new{
items = pagedList,
metaData = pagedList.GetMetaData()
});
这将导致像这样的JSON对象:
This should result in a JSON object like so:
{
"Items": [
{ ... },
{ ... },
{ ... }
],
"MetaData": {
"PageSize": 1,
"PageCount": 2,
"HasNextPage": true,
...
}
}
这篇关于PagedList< T>的Newtonsoft.Json序列化.不包括某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!