我有一个从多个 API 获取数据的应用程序。为了尽量减少类的数量,我需要映射到每个属性。我已经实现了一个简单的 json.net ContractResolver
。但是,当我尝试将属性映射到子属性时,我遇到了一些麻烦。
JSON格式1:
{
"event_id": 123,
"event_name": "event1",
"start_date": "2018-11-30",
"end_date": "2018-12-04",
"participants": {
"guests": [
{
"guest_id": 143,
"first_name": "John",
"last_name": "Smith",
},
{
"guest_id": 189,
"first_name": "Bob",
"last_name": "Duke",
}
]
}
}
JSON格式2:
{
"name": "event2",
"from": "2017-05-05",
"to": "2017-05-09",
"city":"Some other city",
"country":"US",
"guests": [
{
"email":"jane@smith.com",
"firstName":"Jane",
"lastName":"Smith",
"telephone":"1-369-81891"
}
],
}
这是我的模型类:
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public List<Guest> Guests { get; set; }
}
public class Guest
{
public string GuestId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
还有我的解析器:
public class EventResolver : DefaultContractResolver
{
private Dictionary<string,string> PropertyMappings { get; set; }
public EventResolver()
{
this.PropertyMappings = new Dictionary<string, string>
{
{"EventId", "event_id"},
{"StartDate", "start_date" },
{"EndDate", "end_date" },
{"EventName", "event_name" },
{"Guests", "participants.guests"}
};
}
protected override JsonContract CreateContract(Type objectType)
{
return base.CreateContract(objectType);
}
protected override string ResolvePropertyName(string propertyName)
{
var resolved = this.PropertyMappings.TryGetValue(propertyName, out var resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
我知道路径不能代替属性名称。怎么可能这样?