【发布时间】:2021-07-01 12:33:21
【问题描述】:
我有一个public async Task GetCompaniesAsync(),其编码如下:
public async Task GetCompaniesAsync()
{
_getCompaniesSuccessful = false;
var result = await _http.GetAsync($"https://somesite.com/api/companies");
if (result.IsSuccessStatusCode)
{
// I split the code after the suggestion of @mjwills (thanks)
var content = await result.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<StockMarket>(content).Companies;
// at this point, content.Length has a value (e.g. 24429)
// but, obj is null (after JsonConvert)
if (obj != null)
{
_companies = obj.ToList();
_getCompaniesSuccessful = true;
}
}
在其他类中,我使用以下代码:
await MyService.GetCompaniesAsync();
if (MyService.GetCompaniesSuccessful)
{
foreach (var record in MyService.Companies)
{
await Context.Channel.SendMessageAsync($"{record.TickerSymbol,-10}\t{record.CompanyName,-10}");
}
}
但是当我收到以下错误时:异常:值不能为空。 (参数“来源”) 难道是它还没有完成检索数据?请帮忙...????????????
顺便说一下,webapi url 返回的是 JSON 数据,看起来是这样的:
{
"companies": [
{
"ticker": "HEY",
"name": "Hey Corporation",
"status": "open"
},
{
"ticker": "PER",
"name": "Pears Corporation",
"status": "close"
},
{
"ticker": "BRGR",
"name": "Burger Inc.",
"status": "open"
},
]
}
这些是 StockMarket 和 Company 类:
public class StockMarket
{
public StockMarket()
{
}
public ICollection<Company> Companies { get; set; }
}
public class Company
{
public Company()
{
TickerSymbol = "";
CompanyName = "";
Status = "";
}
public string TickerSymbol { get; set; }
public string CompanyName { get; set; }
public string Status { get; set; }
}
【问题讨论】:
-
你能粘贴
StockMarket的定义吗? -
url是否返回json?
-
将
await result.Content.ReadAsStringAsync()分配给一个变量。检查Immediate Window中该变量的值。它的长度是多少? 不要猜测。 -
@LeiYang 我把StockMarket和Company的定义都贴在了帖子的底部。谢谢你的回复:)
-
@JeroenvanLangen 是的 url 返回 JSON,我把它放在 StockMarket 和 Company 类定义之上
标签: c# .net-core json.net discord.net