我可以(主要)使用自定义的DefaultContractResolver,static async getInitialProps({ req }) {
myId = req.params.id
}
反序列化json。唯一的问题是集合StudentPaginatedResultContractResolver
中每个Student
对象中的每个属性都是Students
。
如何使用null
(或任何其他推荐方法)正确解析这些值?
StudentContractResolver
DTO:
var json =
@"{
'TotalCount': 854,
'TotalPages': 9,
'CurrentPage': 1,
'PageSize': 100,
'Result': [
{
'FName': 'Adam',
'Mi':'A',
'LName': 'Ant',
},
{
'FName': 'Bob',
'Mi':'B',
'LName': 'Benson'
}
]
}";
var settings = new JsonSerializerSettings
{
ContractResolver = (StudentPaginatedResultContractResolver) Activator.CreateInstance(typeof(StudentPaginatedResultContractResolver))
};
var result = JsonConvert.DeserializeObject<StudentPaginatedResult>(json, settings);
合同解决者
public class StudentPaginatedResult
{
public int TotalCount { get; set; }
public int TotalPages { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public IEnumerable<Student> Students { get; set; }
}
public class Student
{
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
}
答案 0 :(得分:1)
您可以将StudentPaginatedResultContractResolver
更改为继承自StudentContractResolver
而不是ContractResolverBase
。然后将其构造函数添加到现有的PropertyMappings
字典中,而不是替换它:
public class StudentPaginatedResultContractResolver : StudentContractResolver
{
public StudentPaginatedResultContractResolver()
{
PropertyMappings.Add(nameof(StudentPaginatedResult.Students), "Result");
}
}