我有一个正常工作的HttpResponseMessage返回数据,我的问题是如何计算数据?
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://api.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = httpClient.GetAsync("v1/registrants/search?email=" + email).Result;
return response.Content.ReadAsStringAsync().Result;
}
请帮助。
这是返回的内容:
{
"links" : {
"next" : null
},
"items" : [ ]
}
如果项目为空,则表示计数应为0。
这是当它不为空时返回的内容
{
"links": {
"next": null
},
"items": [
{
"registrantId": 31436518,
"personalId": 38464352,
"firstName": "FirstName",
"lastName": "LastName",
"email": "email@domain.com",
"address": ", Stoney Creek, , 90210, ",
"phone": "9053341529",
"_links": {
"self": "/registrants/31436518"
}
}
]
}
答案 0 :(得分:1)
在继续之前安装Nuget Newtonsoft.Json。
1)将序列化的字符串响应反序列化为JObject
public async Task<JObject> FetchData()
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://api.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = httpClient.GetAsync("v1/registrants/search?email=" + email).Result;
string response = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<JObject>(response);
}
}
2)在其上调用.Count()
方法,如果不存在items
,请使用safe-evaluation operator与null coalescing operator的组合进行后备。
public async Task<int> CalculateCount()
{
JObject responseObject = await FetchData();
return responseObject["items"]?.Count() ?? 0;
}
答案 1 :(得分:0)
您可以使用JSON.net来解析JSON。
首先定义一个对结果进行建模的类:
class ResultModel
{
public List<Item> items { get; set; }
}
然后调用JsonConvert.DeserializeObject<T>(string json)
解析/映射结果:
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://api.com/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = httpClient.GetAsync("v1/registrants/search?email=" + email).Result;
string json = response.Content.ReadAsStringAsync().Result;
ResultModel result = JsonConvert.DeserializeObject<ResultModel>(json);
int count = result.items.Count();
}