【问题标题】:ArgumentException when converting JSON to Model using Newtonsoft in ASP.Net Core在 ASP.Net Core 中使用 Newtonsoft 将 JSON 转换为模型时出现 ArgumentException
【发布时间】:2019-07-03 12:45:01
【问题描述】:

我在我的 ASP.Net Core Web 应用程序和 Web API 中使用 Newtonsoft,但我得到了一个

ArgumentException:无法从 System.String 转换或转换为 TCGInfo.WebUI.Models.TCGModel。

这是我的代码:

创建 JSON:

    public async Task<string> GetTCGList()
    {
        var TCGList = await _manageCardHelper.GetTCGList();
        var json = JsonConvert.SerializeObject(TCGList);
        return json;
    }

读取 JSON:

        var response = await httpClient.GetAsync("GetTCGList");

        if (response.IsSuccessStatusCode)
        {
            var jsonResult = JsonConvert.DeserializeObject<TCGModel>(await response.Content.ReadAsStringAsync());

        }

型号:

public class TCGModel
{
    public string Abbreviation { get; set; }
    public string Name { get; set; }
}

【问题讨论】:

    标签: json asp.net-core json.net


    【解决方案1】:

    根据您获取的路线(“GetTCGList”),我假设您实际上得到了一系列模型,而不仅仅是一个。你需要告诉DeserializeObject

    jsonResult = JsonConvert.DeserializeObject<List<TCGModel>>(await response.Content.ReadAsStringAsync());
    

    【讨论】:

      【解决方案2】:

      从上面的代码中,我只能说JsonConvert.DeserializeObject 应该使用 TCFModel 列表而不是 TCFModel。以下代码行应该可以工作。

      var jsonResult = JsonConvert.DeserializeObject<List<TCGModel>>(await response.Content.ReadAsStringAsync());
      

      【讨论】:

      • 这给了我同样的错误,但只是 TCGModel 它是 TCGMode 列表。但在这一点上,我已经放弃了 API 并转向其他方法。似乎 ASP.Net Core 还没有准备好使用 API。
      猜你喜欢
      • 2017-06-11
      • 2021-08-04
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多