我有一个自定义的合同解析器,用于将我的模型中的属性名称解析为RESTful API调用返回的属性名称。以下是一个示例API调用:
{
"record_id": "f461dc88-2a3c-428c-ad92-1d03477667cf",
"company": "Palm Beach Photographics",
"company_info": {
"images": [
"https://picsum.photos/200/300?image=719",
"https://picsum.photos/200/300?image=653",
"https://picsum.photos/200/300?image=965"
],
"industries": [
"Real Estate",
"Photo/Film",
"Utilities/Energy/Infrastructure",
"Emergency Services"
],
"location_state": "FL",
"overview": "Per fusce luctus diam hac dictum posuere non interdum conubia eleifend, fusce suscipit purus aliquam porttitor amet fames nostra sapien potenti fusce, quisque felis quisque ante fringilla nulla rutrum porta at inceptos mi per mattis rhoncus id."
}
}
我的模型如下:
public class Company
{
public Guid Id { get; set; }
public string Name { get; set; }
public CompanyInfo Info { get; set; }
}
public class CompanyInfo
{
public IEnumerable<Uri> Images { get; set; }
public string State { get; set; }
public IEnumerable<string> Industries { get; set; }
public string Overview { get; set; }
}
public class CustomContractResolver : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; }
public CustomContractResolver(Dictionary<string, string> propertyMappings)
{
PropertyMappings = propertyMappings;
}
protected override string ResolvePropertyName(string propertyName)
{
var resolved = PropertyMappings.TryGetValue(propertyName, out var resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
如何在不使用JsonProperty和其他标签的情况下,使嵌套的company_info
正确绑定到我的模型中呢?当我使用JsonConvert反序列化对象时,我要传入以下属性映射:
private readonly Dictionary<string, string> _propertyMappings = new Dictionary<string, string>
{
{"Id", "record_id"},
{"Name", "company"},
{"Info.Images", "company_info.images"},
{"Info.Industries", "company_info.industries"},
{"Info.State", "company_info.location_state"},
{"Info.Overview", "company_info.overview"}
};
Id和Name正确绑定,但是Info中的任何内容都没有映射。