猿问

如何将非数组 json 反序列化为实现 List<T> 的子类?

我有以下课程:


public class PagedClientModelList<T> : List<T>

{

    public int TotalCount { get; set; }

    public int PageSize { get; set; }

    public int CurrentPage { get; set; }

    public int TotalPages { get; set; }

}

两个不同的 json 字符串将被反序列化为该对象的一个实例:


一个 api GET 请求的 http 内容将被反序列化为 List<T>

api GET 请求的“X-Pagination”标头将反序列化为派生类型的 4 个属性 PagedClientModelList<T>

反序列化为List<T>没问题:


var result = JsonConvert.DeserializeObject<PagedClientModelList<Person>>

                 (httpResponseMessage.Content.ReadAsStringAsync().Result);

对于 json 字符串:


[

  {

    "id": 1,

    "name": "Hans"

  },

  {

    "id": 2,

    "name": "Peter"

  },

  {

    "id": 3,

    "name": "Max"

  }

]

但是,当我想反序列化标头(非数组 json)时,jsonConverter 想再次反序列化List<T>并抛出异常,但我需要将其序列化到子类PagedClientModelList<T>:


if (httpResponseMessage.Headers.TryGetValues("X-Pagination", out var xPagination))

{

    result = JsonConvert.DeserializeObject<PagedClientModelList<Person>>(xPagination.First());


    // throws exception: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type [... because it requires json array]

}

对于相应的标头值:


{

  "totalCount": 12,

  "pageSize": 3,

  "currentPage": 1,

  "totalPages": 4

}

如何将非数组 json 反序列化为实现 的子类List<T>?


四季花海
浏览 214回答 2
2回答

GCT1015

为了继续前进,我实施了以下解决方法:public class PagedClientModelList<T> : List<T>{&nbsp; &nbsp; public PaginationMetadata PaginationMetadata { get; set; }}public class PaginationMetadata{&nbsp; &nbsp; public int TotalCount { get; set; }&nbsp; &nbsp; public int PageSize { get; set; }&nbsp; &nbsp; public int CurrentPage { get; set; }&nbsp; &nbsp; public int TotalPages&nbsp; { get; set; }}现在我可以毫无问题地反序列化:var result = JsonConvert.DeserializeObject<PagedClientModelList<Person>>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(httpResponseMessage.Content.ReadAsStringAsync().Result);if (httpResponseMessage.Headers.TryGetValues("X-Pagination", out var xPagination)){&nbsp; &nbsp; result.PaginationMetadata = JsonConvert.DeserializeObject<PaginationMetadata>(xPagination.First());}
随时随地看视频慕课网APP
我要回答