[英]JsonConvert.DeserializeObject() throwing System.ArgumentNullException: 'Path cannot be null. Parameter name: path' exception. Why?
[英]Why does JsonConvert.DeserializeObject return an error: Exception: Value cannot be null. (Parameter 'source')
我有一個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}");
}
}
但是當我收到以下錯誤時:異常:值不能為空。 (參數'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"
},
]
}
這些是 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; }
}
查看示例,您的 JSON 有一個“name”鍵,但您的 Company 類的屬性稱為“CompanyName”。
嘗試將屬性更改為簡單的名稱,或者用它來裝飾它
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
此外,同樣適用於 TickerSymbol 屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.