2012-06-03 48 views
3

我试图序列化PagedList对象(https://github.com/martijnboland/MvcPaging/blob/master/src/MvcPaging/PagedList.cs)到JSON,像这样:Newtonsoft.Json序列不包括一些属性

PagedList<Product> pagedList = new PagedList<Product>(products, (page - 1), pageSize); 
string json = Newtonsoft.Json.JsonConvert.SerializeObject(pagedList); 

如果我使用上面的代码,在结果我获取正确序列化的Product对象数组。然而下面(的PagedList)的特性不被包含在JSON结果:

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的一部分。

有谁知道为什么?我怎么能在序列化中包含这些属性?

由于

回答

8

串行器看到该PagedList是枚举的,因此它将其序列为JavaScript阵列。为了更容易处理,我在PagedList对象上公开了一个GetMetaData()函数,该函数将返回一个包含上面提到的字段的MetaData对象。这意味着您可以系列化你pagedlist像这样:

string json = Newtonsoft.Json.JsonConvert.SerializeObject(new{ 
    items = pagedList, 
    metaData = pagedList.GetMetaData() 
}); 

这将导致一个JSON对象,像这样:

{ 
    "Items": [ 
     { ... }, 
     { ... }, 
     { ... } 
    ], 
    "MetaData": { 
     "PageSize": 1, 
     "PageCount": 2, 
     "HasNextPage": true, 
     ... 
    } 
} 
+0

任何想法如何反序列化 – AMH

+0

谢谢特洛伊,非常好的实现。 AMH问道,我只是添加了反序列化部分。 – PedroSouki

0

有一个jQuery插件,它是用来激动地做到这一点:

https://github.com/turhancoskun/pagify.mvc

<script type="text/javascript"> 
$(function() { 
    $('#users').pagify({ 
     dataUrl: '/User/UserLis', 
     callBack: function(){ 
      // Ajax remove preloader and some other callbacks 
     }, 
     beforeSend: function(){ 
      // Ajax show preloader and some other function before start 
     } 
    }); 
} 
</script> 

readme.md文件包含一个例子

0

要序列化,只需使用特洛伊的实现。但是,反序列化创建2个新的类别:

public class PaginationEntity<TEntity> where TEntity : class 
{ 
    public PaginationEntity() 
    { 
     Items = new List<TEntity>(); 
    } 
    public IEnumerable<TEntity> Items { get; set; } 
    public PaginationMetaData MetaData { get; set; } 
} 

public class PaginationMetaData 
{ 
    public int Count { get; set; } 
    public int FirstItemOnPage { get; set; } 
    public bool HasNextPage { get; set; } 
    public bool HasPreviousPage { get; set; } 
    public bool IsFirstPage { get; set; } 
    public bool IsLastPage { get; set; } 
    public int LastItemOnPage { get; set; } 
    public int PageCount { get; set; } 
    public int PageNumber { get; set; } 
    public int PageSize { get; set; } 
    public int TotalItemCount { get; set; } 
} 

和反序列化是这样的:

PaginationEntity<TEntity> listPaginated = JsonConvert.DeserializeObject<PaginationEntity<TEntity>>(json) 

,你是好去。