QuickBooks Online对其API使用以下响应:
{
"QueryResponse": {
"Customer": [
{
"GivenName": "Test"
},
{
"GivenName": "Test 2"
}
],
"startPosition": 1,
"maxResults": 2
},
"time": "2018-08-11T16:12:10.808-07:00"
}
我正试图以此创建一个C#模型:
public class QueryResponseRoot<T> where T : IQuickbooksBaseEntity
{
[JsonProperty("QueryResponse")]
public QueryResponse<T> QueryResponse { get; set; }
[JsonProperty("time", Required = Required.Always)]
public DateTimeOffset Time { get; set; }
}
public class QueryResponse<T> where T : IQuickbooksBaseEntity
{
[JsonProperty, JsonConverter(typeof(QuickbooksResponseConverter))]
public IList<T> Results { get; set; }
[JsonProperty("startPosition")]
public Int64 StartPositions { get; set; }
[JsonProperty("maxResults")]
public Int64 MaxResults { get; set; }
}
API有多个实体,所有实体均通过IQuickbooksBaseEntity
接口定义。
问题是,如果得到Customers
,它将返回Customer
作为QueryResponse
对象上的属性,但是如果得到类似Accounts
的东西,则响应看起来像这样:
{
"QueryResponse": {
"Account": [
{
"Name": "Accounts Payable (A/P)"
}
],
"startPosition": 1,
"maxResults": 90
},
"time": "2018-08-11T16:14:55.309-07:00"
}
如何将属性Customer
或Account
或已知列表中的任何其他属性映射到模型中的Results
属性?
(可能)要知道的是,我确实知道我在调用API时会返回哪个属性(即客户或帐户)。
现在,我直接在代码中解决它,但是我不确定将其动态转换是否存在较大的性能问题:
var resultObjectJson = JsonConvert.DeserializeObject<dynamic>(body);
var entityName = typeof(T).Name;
var maxResults = (Int64) resultObjectJson.QueryResponse.maxResults;
var startPositions = (Int64) resultObjectJson.QueryResponse.startPosition;
var results = ((JArray) resultObjectJson.QueryResponse[entityName]).ToObject<List<T>>();
var resultRoot = new QueryResponseRoot<T>
{
QueryResponse = new QueryResponse<T>
{
MaxResults = maxResults,
StartPositions = startPositions,
Results = results
}
};
return resultRoot.QueryResponse;