我有以下类(class):
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” header 将反序列化为派生类型的 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 header 时,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]
}
对应的header值:
{
"totalCount": 12,
"pageSize": 3,
"currentPage": 1,
"totalPages": 4
}
如何将非数组 json 反序列化为实现 List<T>
的子类?
最佳答案
好的,这里有一个替代方案,稍微改变一下你的模型:
public class Person
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class PagedClientModelList<T> where T : class, new()
{
[JsonProperty("totalCount")]
public int TotalCount { get; set; }
[JsonProperty("pageSize")]
public int PageSize { get; set; }
[JsonProperty("currentPage")]
public int CurrentPage { get; set; }
[JsonProperty("totalPages")]
public int TotalPages { get; set; }
[JsonProperty("content")]
public List<T> Content { get; set; }
public PagedClientModelList()
{
Content = new List<T>();
}
}
测试代码:
class Program
{
static void Main(string[] args)
{
string header = @"{
""totalCount"": 12,
""pageSize"": 3,
""currentPage"": 1,
""totalPages"": 4
}";
string content = @"[
{
""id"": 1,
""name"": ""Hans""
},
{
""id"": 2,
""name"": ""Peter""
},
{
""id"": 3,
""name"": ""Max""
}
]";
var modelList = JsonConvert.DeserializeObject<PagedClientModelList<Person>>(header);
modelList.Content = JsonConvert.DeserializeObject<List<Person>>(content);
Console.ReadKey();
}
}
关于c# - 如何将非数组 json 反序列化为实现 List<T> 的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51348779/