3 回答
TA贡献1796条经验 获得超4个赞
的呼唤
all.ReadAsAsync<Object>().Result;
JObject返回一个不能通过简单转换转换为的实例Yelp。而是ReadAsAsync像这样调用
var business = await all.ReadAsAsync<Common.Models.Yelp.Yelp>();
return business;
如果你仍然想调用它,object你可以这样做
var business = await all.ReadAsAsync<object>();
return ((JObject)business).ToObject<Yelp>();
笔记
响应 json 不包含额外的花括号。它只是JObject将它们添加到调试视图中。通过检查将响应读取为字符串的结果很容易检查这一点all.ReadAsStringAsync().Result。
TA贡献1854条经验 获得超8个赞
使用 JSON.NET 的Deserialize 方法使用泛型类型重载将字符串反序列化为所需的 POCO。
public async Task<HttpContent> InvokeApi(string path, HttpAction action, HttpContent content = null, TimeSpan? overrideTimeout = null, string externalServer = null)
{
var sUrl = externalServer == null ? ServerUrl : externalServer;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(sUrl);
if (overrideTimeout.HasValue)
{
client.Timeout = overrideTimeout.Value;
}
//this.Log("Connecting to {0} Api at {1}".Fmt(WebPortalServer, ServerUrl));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
switch (action)
{
case HttpAction.Get:
response = await client.GetAsync(path);
break;
case HttpAction.Post:
response = await client.PostAsync(path, content);
break;
case HttpAction.Put:
response = await client.PutAsync(path, content);
break;
case HttpAction.Delete:
response = await client.DeleteAsync(path);
break;
default:
throw new ArgumentOutOfRangeException("action", action, null);
}
return response.IsSuccessStatusCode ? response.Content : null;
}
}
public async Task<Common.Models.Yelp.Yelp> GetAllBusiness(decimal latitude, decimal longitude)
{
HttpContent all = await _webPortalApiClient.InvokeApi($"businesses/search?limit=10&latitude={latitude}&longitude={longitude}", HttpAction.Get, null, null, "https://api.yelp.com/v3/");
if (all == null)
{
return null;
}
string responseBody = await all.ReadAsStringAsync();
// Deserialize from serialized string into your POCO
var business = JsonConvert.DeserializeObject<Common.Models.Yelp.Yelp>(responseBody);
return business;
}
TA贡献1794条经验 获得超8个赞
var business = all.Result;
var resultString = business.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Common.Models.Yelp.Yelp>(resultString);
- 3 回答
- 0 关注
- 100 浏览
添加回答
举报