【问题标题】:Why does JsonConvert.DeserializeObject return an error: Exception: Value cannot be null. (Parameter 'source')为什么 JsonConvert.DeserializeObject 返回错误:异常:值不能为空。 (参数“来源”)
【发布时间】: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


【解决方案1】:

查看示例,您的 JSON 有一个“名称”键,但您的公司类的属性称为“公司名称”。

尝试将属性更改为简单的名称,或者用这个来装饰它

[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]

此外,TickerSymbol 属性也是如此。

【讨论】:

  • 感谢@peterlange 指出我的错误。这是我第一次尝试使用来自公共 Web 服务的 JSON 数据……我认为 JsonConvert 通过查看属性类型(int、string 等)的序列而不是属性名称来进行转换。谢谢谢谢你帮助我! ??????
猜你喜欢
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多