使用多个DefaultContractResolvers反序列化JSON

时间:2019-09-19 00:54:17

标签: c# json json.net

我可以(主要)使用自定义的DefaultContractResolverstatic 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; }
}

1 个答案:

答案 0 :(得分:1)

您可以将StudentPaginatedResultContractResolver更改为继承自StudentContractResolver而不是ContractResolverBase。然后将其构造函数添加到现有的PropertyMappings字典中,而不是替换它:

public class StudentPaginatedResultContractResolver : StudentContractResolver
{
    public StudentPaginatedResultContractResolver()
    {
        PropertyMappings.Add(nameof(StudentPaginatedResult.Students), "Result");
    }
}

提琴:https://dotnetfiddle.net/APSRfn