为什么 JsonConvert.DeserializeObject 返回错误:异常:值不能为空。(参数"源")



我有一个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}");
}
}

但当我得到以下错误时:异常:值不能为null。(参数'source')可能是它还没有完成数据检索吗?请帮忙。。。

顺便说一下,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"
},
]
}           

这些是股票市场和公司类别:

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; }
}

查看示例,您的JSON有一个"name";键,但是您的Company类的属性被称为";公司名称">

尝试将属性更改为简单的名称,或使用此进行装饰

[JsonProperty("名称",NullValueHandling=NullValueHandler.Ignore)]

此外,TickerSymbol属性也是如此。

相关内容

  • 没有找到相关文章

最新更新