我能够从网址中检索一个json对象。我在检索充满json对象的页面时需要帮助。我发现这个网站https://jsoneditoronline.org/展示了我想返回的页面的json体系结构:
这是我的代码:
namespace iexName.Controllers
{
[Route("api/IexName")]
[ApiController]
public class IexNameController : ControllerBase
{
private IHttpClientFactory _httpClientFactory;
public IexNameController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public IEnumerable<Models.IexTradingStock> GetQuote()
{
string responseString = string.Empty;
var Client = _httpClientFactory.CreateClient();
try
{
responseString =
Client.GetStringAsync($"https://api.iextrading.com/1.0/stock/aapl/chart/1y").Result;
}
catch (HttpRequestException hre)
{
Console.WriteLine(hre.Message);
//TODO do something
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//TODO do something
}
//quit if get content fail
if (responseString == string.Empty) return null;
try
{
var stock = JsonConvert.DeserializeObject<IexTradingStock>
(responseString);
return stock;
}
错误在于“退货;”。我意识到我不知道如何返回所有json对象。
答案 0 :(得分:0)
不久之后,我将其键入stackflow后我意识到该怎么做。这行得通。
namespace iexName.Controllers
{
[Route("api/IexName")]
[ApiController]
public class IexNameController : ControllerBase
{
private IHttpClientFactory _httpClientFactory;
public IexNameController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public IEnumerable<Models.IexTradingStock> GetQuote()
{
string responseString = string.Empty;
var Client = _httpClientFactory.CreateClient();
try
{
responseString =
Client.GetStringAsync($"https://api.iextrading.com/1.0/stock/aapl/chart/1y").Result;
}
catch (HttpRequestException hre)
{
Console.WriteLine(hre.Message);
//TODO do something
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//TODO do something
}
//quit if get content fail
if (responseString == string.Empty) return null;
try
{` List<IexTradingStock> stock =
JsonConvert.DeserializeObject<List<IexTradingStock>>(responseString);
return stock;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//TODO do something
return null;
}
}
}
}`