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

json, json.net, pagedlist

Solution

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,
        ...
    }
}

Problem

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

Original source