我正在使用Newtonsoft.Json解析一些API响应,并且它们似乎具有非常规则的结构,只是数组属性名称会根据返回类型而变化。几个响应示例(带有虚假/空数据):
顾客:
{
"success": true,
"message": "Records Retrieved Successfully",
"data": {
"total_count": "1",
"customer": [
{
"id": "1234",
"accountId": "220",
"email": "[email protected]",
"name": "JSON Voorhees",
"company": "Test Company",
"customFieldsValues": [
{
"value": "Some Guy",
"field": {
"id": "69",
"name": "SalespersonID",
"label": "Account Manager"
}
}
]
}
]
}
}
发票:
{
"success": true,
"message": "Records Retrieved Successfully",
"data": {
"total_count": "0",
"invoice": []
}
}
您会在第一个中注意到,数组的属性名称是“ customer”,在第二个中,它是“发票”(我们没有任何发票,所以我不知道它的确切结构是什么)对象仍将是)。
我的最终目标是反序列化为这样的类结构:
public class Response {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
public class Response<T> : Response {
public List<T> Data { get; set; }
}
由于这不能通过简单的DeserializeObject()
调用直接完成(因为业务对象的数组包含在该中间的“ data”属性中),这似乎离所需的对象有点近,但是问题在于该[JsonProperty()]
属性的移动目标:
public class Response {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
public class Response<T> : Response {
public ResponseData Data { get; set; }
}
public class ResponseData<T> {
[JsonProperty("total_count")]
public int TotalCount { get; set; }
[JsonProperty("???")] //Moving target
public List<T> Data { get; set; }
}
实现这一目标的最明智的方法是什么?
好的,这是可行的,但这当然不是我见过的最漂亮的东西(对转换为字典的中间步骤并不完全满意)。如果有人知道这样做的更好方法,请暂时保留此问题。
各种对象:
public class Response {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}
public class Response<T> : Response {
[JsonProperty("data")]
[JsonConverter(typeof(DataConverter))]
public List<T> Data { get; set; }
}
public class DataConverter : JsonConverter {
public override bool CanConvert(Type objectType) {
return typeof(List<object>).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
Dictionary<string, object> data = (Dictionary<string, object>)serializer.Deserialize(reader, typeof(Dictionary<string, object>));
foreach (KeyValuePair<string, object> kvp in data) {
if (kvp.Key != "total_count") {
return ((JToken)kvp.Value).ToObject(objectType);
}
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException();
}
}
然后获取响应:
public Response<Customer> GetCustomers() {
string response = SendRequest("/api/v1/customers");
Response<Customer> aresponse = JsonConvert.DeserializeObject<Response<Customer>>(response);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句