Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json serialization of PagedList<T> is not including some properties

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

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

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?

Thanks

like image 243
LeoD Avatar asked Oct 21 '25 04:10

LeoD


1 Answers

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

This should result in a JSON object like so:

{
    "Items": [
        { ... },
        { ... },
        { ... }
    ],
    "MetaData": {
        "PageSize": 1,
        "PageCount": 2,
        "HasNextPage": true,
        ...
    }
}
like image 183
Troy Avatar answered Oct 22 '25 18:10

Troy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!